gpt4 book ai didi

javascript - Express.js : POST data sent as KEY ONLY in my req. 主体对象

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:38 25 4
gpt4 key购买 nike

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

我很困惑,不知道如何继续。

谢谢!

最佳答案

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

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

关于javascript - Express.js : POST data sent as KEY ONLY in my req. 主体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59817947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com