我在后端使用node.js和Express.js,并尝试通过AJAX从客户端进行服务器调用。
所以我有一个可以与 AJAX 配合使用的 POST 请求:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
客户端/AJAX 请求:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
userInputForm
来自 HTML 表单。
这个 POST 请求工作正常。但我想将其更改为 GET 请求。如果我将 app.post
更改为 app.get
,并将 AJAX 调用中的 type
更改为 GET
,我收到此 500 错误:
GET/createNewThing?userInput=
500
最佳答案
当您发出 GET 请求时,数据将出现在(请求 header 中的 URL 的)查询字符串中。它不会出现在请求正文中。没有请求正文。
当您尝试读取请求正文时,您正在尝试访问 undefined object 的属性,这会触发异常并导致内部服务器错误。
This answer explains how to read a query string :
var id = req.query.id; // $_GET["id"]
所以
var userInput = req.query.userInput;
关于javascript - 获取 AJAX GET 请求以与 Express.js 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40338940/