javascript - 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"}': '' }
我很困惑,我不太确定如何进行。
谢谢!
解决方案
一切似乎都很好,您必须将 Header 声明为json,
http.setRequestHeader("Content-type", "application/json");
推荐阅读
- python - 有没有一种方法可以在不使用热编码器的情况下训练 RNN?
- java - mysql 连接器没有连接到我的 xxamp localhost
- python-3.x - Python ConfigParser.write() 缺少 1 个必需的位置参数“fp”?
- google-pagespeed - 出现错误 - Lighthouse 返回错误:内部:APP::1:渲染器异常终止,状态 = 崩溃 exit_code = 1
- cplex - Cplex如何在约束中使用变量进行索引
- mysql - MySQL 将一张表连接到另外两张表
- wordpress - Wordpress - woocommerce - myaccount/orders-list.php - 获取产品图片
- metadata - 从自动查询元数据中隐藏类型
- python - 使用 for 循环出现意外的 KeyError,但手动时没有
- angular - 如果我将鼠标悬停在 Plotly 中,如何显示与图例中所述不同的跟踪名称?