Strange problem with express app post example.Have different behaviors with curl and fetch (browser api)


I have a simple express app,

// index.js
import express from "express";
// create the express application
const app = express();
// serve static files
// set builtins post"/builtins", (req, res) => {
  console.log("debug request body builtins", req.body);

// start the server
app.listen(3333, () => console.log("Start express app"));

And a simple index.html page

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      fetch("http://localhost:3333/builtins", {
        body: JSON.stringify(["wojtyla", "ratzinger", "madre teresa"]),
        mode: "no-cors",
        headers: {
          "Content-Type": "application/json",
        method: "POST",
        .then((t) => t.text())
        .then((t) => document.write(`<h1>Got response ${t}</h1>`));

I start the server as usual: node index.js. Then open a browser at http://localhost:3333/index.html.

Everything seems to be ok, but when I open the logs of the express app, I check the following:

debug request body builtins {}

But I was expecting to receive:

debug request body builtins [ 'wojtyla', 'ratzinger', 'madre teresa' ]

The strange part in this is that when I curl:

curl -d '["wojtyla","ratzinger", "madre teresa"]' "Content-Type: application/json" -X POST http://localhost:3333/builtins

I receive the expected answer in the express app logs (debug request body builtins [ 'wojtyla', 'ratzinger', 'madre teresa' ]).

What am I doing wrong here? Can someone help me?

Thanks in advance


You said:

mode: "no-cors",

Which tells fetch that if you try to do anything that requires permission from the server (using CORS) then it should fail silently.

Setting the content-type to anything that isn’t a supported value of the HTML form element’s enctype attribute is one of those things.

Since you fail to set the content-type request header, the browser isn’t telling the server it is sending application/json, so the JSON parsing middleware doesn’t kick in.

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published