首页 > 解决方案 > Express.js:POST 数据仅在我的 req.body 对象中作为 KEY 发送

问题描述

我目前的 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"}': '' }

我很困惑,我不太确定如何进行。

谢谢!

标签: javascriptnode.jsajaxreactjsexpress

解决方案


一切似乎都很好,您必须将 Header 声明为json

http.setRequestHeader("Content-type", "application/json");

推荐阅读