简体   繁体   English

来自 nodejs 中的 post 请求的未定义正文

[英]Undefined body from post request in nodejs

I created the API in node js and in the POST method getting the body as undefined.我在节点 js 和 POST 方法中创建了 API,将主体设为未定义。 How can I get the value that is passed using the fetch?如何获取使用 fetch 传递的值?

code for NodeJs------------------------------------------- NodeJs的代码-------------------------------------------

const express=require('express');
const app=express()
const port=3000
const fs=require('fs');


app.get('/',(req,res)=>{
    res.send('hello world!');
});

app.get('/movies',(req,res)=>{
    fs.readFile(__dirname+'/movies.json','utf-8',(err,data)=>{
        res.send(data);
    });
});

app.post('/movies',(req,res)=>{
    console.log(req.body);
});

app.listen(port,()=>{
    console.log(`app listening at http://localhost:${port}`)
});

code for HTML------------------------- HTML代码------------------------

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <form onsubmit="submitted(event)">
        <input id="field" type="text" required="true">
        <button type="submit">save</button>
    </form>
</body>
<script>
    function submitted(e){
        e.preventDefault();
        const value=document.getElementById('field').value;
        await fetch('http://localhost:3000/movies',{
            method:'POST',
            body:{value},
            mode:'no-cors',
            headers:{
                "Content-Type" : "application/json",
                'Access-Control-Allow-Origin':'*'
            }
        });
    }
</script>
</html>

You need to use a middleware to parse the body correctly.您需要使用中间件来正确解析正文。 It looks like you're sending JSON, so you'll need the bodyParser middleware provided by express.看起来您正在发送 JSON,因此您需要express提供的bodyParser中间件。

Well you have got 2 problems:那么你有两个问题:

1 Problem: 1 问题:

You need to stringify your body like你需要把你的身体像

  body:JSON.stringify({value})

2 Problem: 2 问题:

In express you need to parse your body.在 express 中,你需要解析你的身体。 For that express provides .json()对于那个快递提供.json()

const express=require('express');
const app=express()
const port=3000
const fs=require('fs');

app.use(express.json())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM