What is wrong with my express parse setup?

Viewed 89

Server

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

app.listen(4000, () => console.log("listening at 4000"));
app.use(express.static("public"));
app.use(express.json({limit: "1mb"})); 


//POST method route
app.post("/clientApi", (req, res) => {
  // res.send("POST request to the homepage")
  console.log(req.body);
});

Client

function checkData() {
    let summoner = playerName.value;

    let fetchData = {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(summoner),
    }

    fetch("/clientApi", fetchData)
    .then(response => response.json())
    .then(data => {
        console.log("Success: ", data);
    });   
}

Everything worked fine until I tried calling for Express.json but I don't see any syntax error. The client side could send data to the server. But it was too much data so I used "req.body" to try and get exactly what I wanted, but on the terminal its undefined. So that's when I decided to try using express.json which is where the error came up.

Error Message

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

4 Answers

You forgot the {} after app.listen(4000, () => {console.log("listening at 4000")}); that should fix it

Actually you forgot to make proper JSON formate at client site:

function checkData() {
let summoner = playerName.value;
let sendData = {};
sendData.summoner = summoner;

let fetchData = {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(sendData),
}

fetch("/clientApi", fetchData)
.then(response => response.json())
.then(data => {
    console.log("Success: ", data);
});   

}

NOTE: Data you pass inside JSON.stringify() should a proper JSON Object. So that it can parse on the other side.

Shouldn't fetch("/clientApi", fetchData) include http://localhost:4000/clientApi?

Try sending an object rather than just a string stringified such as

<script>
    const playerName = {
        value: "foobar"
    };

    function checkData() {
        const summoner = { ...playerName };

        const fetchData = {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(summoner),
        }

        fetch("/clientApi", fetchData)
            .then(response => response.json())
            .then(data => {
                console.log("Success: ", data);
            });
    }

    checkData();
</script>

Express won't be able to decode it otherwise.

Related