最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Non Expected Format of JSON Received By Express App (Sent By Fetch API) - Stack Overflow

programmeradmin1浏览0评论

I am new to nodejs/express and I have stumbled across a seemingly simple, yet annoying, problem in a web app I am developing. Essentially, I am trying to send a post request to an Express App that contains a JSON file in it's body. When using Thunder Client to send a Post Request, the JSON is perfectly formatted. However, when I try to send a post request using the fetch api, the body of the resquest is formatted in a diffrent (wrong?) way.

Here is the file that I am using to send the fetch post request:

Here is the request made in thunder client

express app code

This is the result after sending in a post request via thunder client and then a post request made by fetch

Due to the current format the fetch request presents the JSON file in, I can't easily acess the contents of the JSON file. It seems the entire sent JSON file is placed in the first variable name of the received JSON file. I was thinking it may be possible to extract that string and then parse it using JSON.parse(), but I feel like there is a much more elegant way of fixing this.

Thank you for your time and help!

I am new to nodejs/express and I have stumbled across a seemingly simple, yet annoying, problem in a web app I am developing. Essentially, I am trying to send a post request to an Express App that contains a JSON file in it's body. When using Thunder Client to send a Post Request, the JSON is perfectly formatted. However, when I try to send a post request using the fetch api, the body of the resquest is formatted in a diffrent (wrong?) way.

Here is the file that I am using to send the fetch post request:

Here is the request made in thunder client

express app code

This is the result after sending in a post request via thunder client and then a post request made by fetch

Due to the current format the fetch request presents the JSON file in, I can't easily acess the contents of the JSON file. It seems the entire sent JSON file is placed in the first variable name of the received JSON file. I was thinking it may be possible to extract that string and then parse it using JSON.parse(), but I feel like there is a much more elegant way of fixing this.

Thank you for your time and help!

Share Improve this question asked Mar 31 at 17:39 RyanRyan 11 New contributor Ryan is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 1
  • Pls, do not share image. instead paste the code. Screen readers can't interpret code in images.also other users can directly test/debug the code instead of retyping it from an image – Yilmaz Commented Mar 31 at 21:20
Add a comment  | 

2 Answers 2

Reset to default 1

Choosing the proper content type is essential for HTTP/HTTPS requests. For instance, when performing any request through a JSON body, in your client code, you have to specify the Content-Type header as in the code above (in your case, application/json, not x-www-form-urlencoded):

const response = await fetch("http://127.0.0.1/example_post", {
    method: "POST",
    body: JSON.stringify([0, 1, 2, 3, 4, 5]),
    headers: { "Content-Type": "application/json;charset=utf-8" } })

A couple of issues in your code.

#1 In html,

Incorrect Content-Type Header

From

headers: {
    "Content-Type": "application/x-www-form-urlencoded",
},

To

headers: {
    "Content-Type": "application/json",
}

#2 In server.js,

The issue with your original server.js file not sending a 200 OK response was due to how your Express server handled the POST request.

res.status(200).json({ message: "Request received", data: req.body });

Here are full code update base on your code index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <button id="post-btn">I'm a button</button>
    <div id="response-message" style="margin-top: 10px; font-weight: bold;"></div>

    <script>
        const button = document.getElementById('post-btn');
        const responseMessage = document.getElementById('response-message');

        button.addEventListener('click', async () => {
            try {
                const test = {
                    key: 5
                };

                const response = await fetch('http://127.0.0.1:8080/example_post', {
                    method: "POST",
                    body: JSON.stringify(test),
                    headers: {
                        "Content-Type": "application/json",
                    },
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                console.log('Completed!', data);

                // Display the returned message in the HTML
                responseMessage.textContent = `Message: ${data.message}, Data: ${JSON.stringify(data.data)}`;
            } catch (err) {
                console.error(`Error: ${err}`);
                responseMessage.textContent = `Error: ${err.message}`;
            }
        });
    </script>
</body>
</html>

server.js

import express from 'express';
import cors from 'cors';

// Making an app with express
const app = express();

// Enable CORS for all routes
app.use(cors());

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

// POST request handler for "/example_post"
app.post("/example_post", async (req, res) => {
    console.log("ping");
    console.log(req.body);
    // Send a 200 OK response with a success message
    res.status(200).json({ message: "Request received", data: req.body });
});

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Problem');
});

// Start the server
app.listen(8080, () => {
    console.log("Server up on http://localhost:8080");
});

package.json

{
    "type": "module",
    "dependencies": {
        "cors": "^2.8.5",
        "express": "^4.18.2"
    },
    "devDependencies": {
        "nodemon": "^2.0.22"
    }
}

run result

发布评论

评论列表(0)

  1. 暂无评论