如何在服务器端提取 req.body(我正在使用 fetch)?



我正在制作一个由单独的前端和后端组成的项目。从前端,我通过 fetch 发出一个 POST 请求,该请求应该将字符串"ORANGE"发送到后端,然后后端应该将其记录到控制台。我无法让后端控制台记录字符串。我在devtools中查看了请求,字符串"ORANGE"被埋在"请求有效载荷"下。请求本身发送正常。如何实际访问字符串以便可以使用它执行操作?(例如,存储在数据库中(

//FRONTEND
const commentForm = document.getElementById("editform");
commentForm.addEventListener('submit', function(e) { 
e.preventDefault();
fetch('http://localhost:3000/posts/:id', {
mode: 'cors',
method: 'post',
headers: {
"Content-type": "text/plain;charset=UTF-8"
},
body: "ORANGE"
}).then(function(response) {
if (response.ok) {
console.log("response.ok was true: "+ response)
} else {
let error = new Error(response.statusText)
error.response = response
throw error
}
})
});
//BACKEND
router.post('/posts/:id', function(req, res, next) {
console.log('What do I put here to get ORANGE logged?!')
//On the server side I tried some console.log tests.
//console.log("req is " + req);               //req is [object Object]
//console.log("type of req is " + typeof req); //type of req is object
//console.log(JSON.parse(req)); //SyntaxError: unexpected token o in JSON at position 1  
res.send('whatever. I want ORANGE.')
}

尝试以下操作:

  1. 在服务器.js文件中使用正文解析器。

  2. 发送帖子请求content-type如下json

    headers: { Content-Type: application/json }

正文应为 JSON

body: {"color":"ORANGE"}

  1. 在您的路线中只需打印

    console.log(req.body.color)

默认情况下,Express 不会处理请求的正文。您需要加载模块才能显式执行此操作。

由于您使用的是纯文本,因此可以使用正文解析器模块。这将在请求上创建一个body属性:

const bodyParser = require('body-parser');
router.use(bodyParser.text({type: 'text/plain'}))
router.post('/posts/:id', function(req, res, next) {
console.log(req.body);
res.send('Response')
});

但请注意,通常最好使用结构化数据格式(如 JSON(而不是纯文本。

在Express 4.16中,不再需要正文解析器模块。获得身体所需要的只是:

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

在获取中使用"Content-type": "application/x-www-form-urlencoded"否则 CORS 将发送预检并给您带来困难。(有关此谷歌 CORS 简单请求要求的更多信息(。

正如 fetch(( 文档中解释的那样:

这只是一个 HTTP 响应,而不是实际的 JSON。提取 JSON 正文 来自响应的内容,我们使用 json(( 方法(在 Body mixin 上定义, 它由请求和响应对象实现。

const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
console.log(JSON.stringify(myJson));

因此,响应中没有正文对象,只有一个 JSON 对象,即您的主体。

相关内容

最新更新