我正在尝试在节点服务器上处理post ajax请求。我的问题是,我正在获取请求主体“未定义”。请帮助我了解我做错了什么。以下是我正在使用的代码。
function sendRequest(){
let http = new XMLHttpRequest();
let url = 'http://<hostname>:3000/checkRequest';
let data = {};
data.name = "nameString";
data.age = "ageString";
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.send(JSON.stringify(data));
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState === 4 && http.status === 200) {
alert(http.responseText);
}
};
}
请求处理程序代码:
// create express app
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
// middleware route that all requests pass through
app.use((request, response, next) => {
console.log('Server info: Request received');
let origin = request.headers.origin;
// only allow requests from trusted origins
if (originWhitelist.indexOf(origin) > -1) {
response.header('Access-Control-Allow-Origin', origin);
}
// only allow get and post requests, separate methods by comma e.g. 'GET, POST'
response.header('Access-Control-Allow-Methods', 'GET, POST');
response.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
response.header('Access-Control-Allow-Credentials', true);
// push through to the proper route
next();
});
app.post('/checkRequest', (request, response) => {
console.log(request.body.name) //undefined
}
答案 0 :(得分:1)
您正在发送内容类型为JSON.stringify
的{{1}}结果。如果要提交JSON,请将内容类型更改为application/x-www-form-urlencoded
。如果要提交经过编码的url,请使用application/json
而不是new URLSearchParams(data).toString()
。
我个人建议以JSON格式发送数据。
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/toString
答案 1 :(得分:0)
我需要进行以下更改:
1:使用内容类型json: http.setRequestHeader('Content-type','application / json');
2:我需要在节点应用程序中添加请求类型“ OPTIONS”,因为如果我们更改默认的内容类型浏览器,则在发送实际的发布请求之前会发送一个额外的“ OPTIONS”类型请求(添加了参考请求屏幕截图)。
有关更多详细信息,请参见:https://upload.wikimedia.org/wikipedia/commons/c/ca/Flowchart_showing_Simple_and_Preflight_XHR.svg
更新的allow方法为:
response.header('Access-Control-Allow-Methods','GET,POST,OPTIONS');