简体   繁体   中英

Node.js POST request coming back as “{}”

Started using node.js and trying the use the POST request with a fetch but when I run it, it just comes back as {} in the console Server side code -->

const express = require("express")
const app = express()



app.listen(3000, () => console.log("listening at 3000"))
app.use(express.static("public"))
app.use(express.json())



app.post("/api", (request,response) => {
    console.log("Made the POST")
    console.log(request.body)
})

the fetch -->

async function submitValues(){
    const start = document.getElementById("start").value;
    const end = document.getElementById("end").value
    // console.log(start,end)
    // findShortestPath(graph, start, end)
    data = {start, end}
    
    options = {
        method: "POST",
        headers: {
            "Content-Type":"applcation/json"
        },
        body: JSON.stringify(data),
        
    }
    
    await fetch("/api", options);
    
    
}

This is what i've written but just cant figure it out

First you need to install Node.js body parsing middleware:

$ npm install --save body-parser

and then:

const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.post("/api", (request,response) => {
    console.log("Made the POST")
    console.log(request.body)
})

This method doesn't return anything, so not sure why you're surprised this API returns nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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