简体   繁体   English

为什么我无法从 req.body 检索数据

[英]Why i can not retrieve data from req.body

What i want to do is to read the property name of the request i send to my express.js server.Here is how i pass the json data to a post request.我想要做的是读取我发送到我的 express.js 服务器的请求的属性名称。这是我将 json 数据传递给发布请求的方式。

document.querySelector('#checkout').onsubmit= async e =>{
    const form = new FormData(document.querySelector('#checkout'))
    let user = createUserInfo(form),
    

    order = {
       name: "Test_Name"
    }

    fetch("/checkout/create-order", {
        method: "POST",
        mode: "same-origin",
        redirect: 'manual',
        headers:{
            "Content-Type": "application/json"
        },
        body: JSON.stringify(
            {
                order: order,
                user: {
                   name:"test_Name"
                }

            }
        )
    }).then(res=>{
       res.ok
    }).then(data=>{
        console.log(data)
    })
}

And this is how i read it using express.js:这就是我使用 express.js 阅读它的方式:

app.use(express.json());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
const YOUR_DOMAIN = 'http://localhost:4242/checkout.html';

app.post('/checkout/create-order', async (req, res) => {
  console.log(req.body.order.name)
}

When i try to read the name property i get an error.当我尝试读取 name 属性时,出现错误。

C:\xampp\htdocs\server.js:9
  console.log(req.body.order.name)
                             ^

TypeError: Cannot read properties of undefined (reading 'name')

Add e.preventDefault() to the beginning of the onsubmit handler.e.preventDefault()添加到onsubmit处理程序的开头。

By default, when the user clicks a form submit button, the browser will send a URL encoded POST request to the URL defined in the form's action attribute (or if there is no action , the current page).默认情况下,当用户点击表单提交按钮时,浏览器会发送一个 URL 编码的 POST 请求到表单的action属性中定义的 URL(或者如果没有action ,则为当前页面)。

<form action="/somewhere_else"></form>

Your express code is seeing the request sent from the browser, which doesn't have any of the values you defined in the fetch request.您的快速代码正在查看从浏览器发送的请求,该请求没有您在获取请求中定义的任何值。

This also causes the page to reload and interrupt your fetch request code before its sent.这也会导致页面在发送之前重新加载并中断您的获取请求代码。 By adding event.preventDefault() you suppress this behavior and your code should run as expected.通过添加event.preventDefault()您可以抑制此行为,并且您的代码应该按预期运行。

PS You don't need to use both express.json() and bodyparser.json() . PS您不需要同时使用express.json()bodyparser.json() Body-parser is included with Express, so both of those middlewares are doing the same thing. Body-parser 包含在 Express 中,因此这两个中间件都在做同样的事情。 You can also use express.urlencoded() instead of bodyparser.urlencoded() .您也可以使用express.urlencoded()而不是bodyparser.urlencoded()

Your server-side code is correct in my opinion, but a small tip, you don't need to use bodyparser.json() and express.json() both do the same thing.我认为您的服务器端代码是正确的,但是一个小提示,您不需要使用bodyparser.json()express.json()都做同样的事情。 just chose one and stick to it.只是选择了一个并坚持下去。

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

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