当我从我的React应用程序发送提取请求时,NodeJS服务器没有收到任何参数。。。
反应:
fetch('http://xxx:5000/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'url': 'admin@domain.com', 'password': '12345' }) // formData
})
节点:
const bodyParser = require('body-parser')
const urlencodedParser = bodyParser.urlencoded({ extended: false })
const app = express()
app.post('/', urlencodedParser, async (req, resp, next) => {
const url = req.body.url
console.log(url) // undefined
const urlIdPattern = /\d+/g
}
当我直接从表单标记发送请求时,它可以正常工作
<form action="xxx" method="POST">
<input name="url">
</form>
您使用了错误的解析器。 由于要以application/json
的形式发送数据,因此应该使用body-parser
中的json
而不是urlencoded
。
您应该这样使用它(以全局应用它)。
const bodyParser = require('body-parser');
app.use(bodyParser.json();
或者像这样,如果您想要将中间件应用到那个特定的路由。
app.post('/', bodyParser.json(), async (req, resp, next) => {...
当我直接从表单标记发送请求时,它可以正常工作
这是因为当您提交表单时,数据是以urlencoded
的形式发送的(而不是以application/json
)。
这应该能奏效。
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', async (req, resp, next) => {
const url = req.body.url
console.log(url) // undefined
const urlIdPattern = /\d+/g
}