【发布时间】:2020-05-06 03:32:18
【问题描述】:
我目前的 POST 请求有问题。
我有一个简单的函数,负责使用 AJAX 将数据发送到我的服务器。
handleSubmit(event) {
var http = new XMLHttpRequest(); // object allwos us to make http requests
//Lets make a request
http.open("POST", "http://localhost:3000/register", true);//set up the request for us: type of request we want, where we want the data from, do we want it to be sync or async?
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//each time the ready state changes on the http object, it will fire this function.
http.onreadystatechange = function(){
console.log(http); // lets see the ready state changing...
//once the ready state hits 4(request is completed) && status is 200 (which is okay), lets do something with data.
if(http.readyState == 4 && http.status == 200){
}else{
console.log('Error: ' + http.status); // An error occurred during the request.
}
}
let user = {
email: "john@gmail.com"
};
http.send(JSON.stringify(user));
}
我的服务器端代码非常简单,并且包含一个 POST 端点。
const express = require('express')
const app = express()
const port = 3000
//Body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({extended: true}))
app.post('/register', (req, res) => {
console.log(req);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
现在,一旦 handleSubmit 触发,我的对象的 req 主体就变成了:
{ '{"email":"john@gmail.com"}': '' }
我很困惑,我不太确定如何进行。
谢谢!
【问题讨论】:
-
我想到的只是一个提示。删除 Json.stringfy()
-
我在前面尝试了相同的代码,它发送的正文恰到好处,所以,主要是后端问题,尝试将
{type: "application/json"}作为express.json()的参数传递,并确保它是前面一样
标签: javascript node.js ajax reactjs express