我将 Node JS Express 用于后端,将纯 HTML 用于前端。单击按钮后,我正在尝试通过 Node JS 将表单数据发送到 MongoDB。
客户端 [HTML]
<a href="javascript:void(0);" onclick="sendData();" id="get-marker-value" class="btn pxp-hero-contact-form-btn">Get Market Value</a>
<script type="text/javascript">
function sendData(event){
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let phone = document.getElementById("phone").value;
let address = document.getElementById("address").value;
if(name != '' || email != '' || phone != '' || address != ''){
let formData = JSON.stringify({
name: name,
phone: phone,
email: email,
address: address
});
let url="<SERVER_URL>/listing/add_listing";
fetch(url, {
method: 'post',
body: formData,
headers:{"Content-Type" : "application/json"}
}).then(response => response.json())
.then( (result) => {
console.log('success:', result);
$('#get-marker-value').addClass('hide');
$('#get-marker-value-success').addClass('show');
})
.catch(error => console.log('error:', error));
}
else{
}
}
</script>
在服务器端,
var listingRouter = require('./routes/listing');
app.use('/listing', listingRouter);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE" // what matters here is that OPTIONS is present
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`)
})
路线 - 列表
router.post('/add_listing', function(req, res) {
console.log("Post Request");
console.log(req.body);
const name = req.body.name;
const phone = req.body.phone;
const email = req.body.email;
const address = req.body.address;
const date = new Date();
const newListing = new Listing({
name,
phone,
email,
address,
date,
});
newListing.save()
.then(() => res.json('Listing added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
该代码在本地运行良好,但在 Heroku 中存在问题。