这是我使用 ajax 和 node.js 的第一个项目,到目前为止我所有的 POST 请求都是通过表单提交完成的。
我现在尝试使用 $.ajax
发送 POST
并传递字符串“cocktailid”供 server.js
在 div click()
之后使用。
我想知道实现这一目标的最简单方法是什么。
Ajax代码
$(".col-sm").click(function(){
//Append to console a log that cocktail div has been clicked.
console.log("Cocktail Clicked.");
console.log(this);
//Create variable to hold id of cocktail div clicked
var cocktailid = $(this).attr('id');
cocktailid = cocktailid.replace(/\s+/g, '_');
cocktailid = cocktailid.replace(/'/g, '');
alert(cocktailid);
$.ajax({
type: 'POST',
url: '/adddrink',
data: { "field1": cocktailid},
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
console.log('success');
console.log(cocktail + 'sent.');
console.log(JSON.stringify(data));
}
});
})
};
服务器.js
app.post('/adddrink', function(req, res){
console.log(req.body);
});
我尝试以几种不同的格式发送数据,但遇到了不同的问题,目前我的服务器显示以下错误:
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:157:10)
at parse (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:83:15)
at /home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:224:16)
at done (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:160:13)
at endReadableNT (_stream_readable.js:1101:12)
at process._tickCallback (internal/process/next_tick.js:152:19)
现在我只想展示我可以访问 Node 服务器上的字符串。
我尝试四处寻找解决方案,在尝试之后,我希望我确实使我想要实现的目标变得过于复杂,任何帮助将不胜感激!
最佳答案
您必须使用:JSON.stringify
上data
$.ajax({
type: 'POST',
url: '/adddrink',
data: JSON.stringify({
"field1": cocktailid
}),
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {}
});
没有它,有效负载是 field1=yes
而不是{"field1":"yes"}
这就是为什么你会得到 SyntaxError: Unexpected token # in JSON at position 0
因为您没有发布有效的 JSON。
对于更详细的错误,您可以在之后添加错误处理中间件body-parser
处理 JSON 错误。
app.use(bodyParser.json());
app.use((err, req, res, next) => {
// Body parser middleware Error
if(err instanceof SyntaxError) {
// err.body contains the actual body that was posted
// which won't be a valid JSON.
console.error(`Invalid JSON: ${err.body}`);
return res
.status(400) // Bad request
.send({
message: 'Invalid JSON'
});
}
next();
});
关于javascript - 从 Ajax Post 请求访问 Node.js 服务器上的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49967112/