我正在尝试将数据从React发送到Node js。我正在使用Ajax。我没有通过Node.js获取数据
这是我在React上的代码:
让id = item.id
$.ajax({
url: '/postid',
type: 'POST',
data: id
});
console.log('React id : ' + id);
我在Node.js上的代码
app.post('/postid', function (req, res) {
console.log("node js ok");
var getId = req.body.id; // here, i don't get the id value
console.log("id Node js : " + getId);
});
你知道吗?
谢谢
答案 0 :(得分:1)
Do it like this at the frontend:
$.ajax({
url: '/postid',
type: 'POST',
data: JSON.stringify({ id: 'id here' })
});
Use body-parser
at the node js server otherwise, you will not be able to get parameters from the request body.
答案 1 :(得分:1)
You should probably use more modern approach like FetchAPI. Use it with Polyfill, because it is not fully supported in all the browsers. With fetch your code will look like this:
fetch('/postid', {
method: 'POST',
// headers: {} <-- You can include some headers if you want
body: JSON.stringify({id: id})
}).then(function(response) {
return response.json();
}).then(function(json) {
// json -> is your response from server
}).catch(function(error) {
// Handle errors here
});
答案 2 :(得分:0)
Can you try this
$.ajax({
url: '/postid',
type: 'POST',
data: {"id": id}
});
console.log('React id : ' + id);