problems sending the data [nodejs]

23 views Asked by At

I have a problem with bodyparser. I'm building a simple login app, but when I made the fetch, all go down... When I send , the app reach the endpoint but doesn't send the data. Here is the code.

let url;
const get_url = () => {
    let cookies = (document.cookie).split(";");
    cookies.map(cookie => {
        cookie = cookie.trim()
        if (cookie.includes("url=")) {
            url = cookie.replace("url=", "");
            url = decodeURIComponent(url);
            url = url.replaceAll('"', "");
        }

    })
}

document.getElementById("send").onclick = async () => {
     fetch(`${url}create`, {
        method: "post",
        body: JSON.stringify({ perro: 123 })

    }).then(re => re.json()).then(r => console.log(r))
}

get_url()

The server url is obtain from a cookie:

router.get("/create", (req, res) => {
    const exp = new Date(Date.now() + (5 * 1000));
    res
        .cookie("url", JSON.stringify(process.env.SERVER_URL), { expires: exp, secure: true })
        .cookie("cosa", "asd")
        .sendFile(path.join(__dirName, "./public/creator.html"));

})

router.post("/create", (req, res) => {
    console.log(req.body);
    res.json({cosa: 123})
})

and here is the index.js

import "dotenv/config";
import express from "express";
import cors from "cors";
import colors from "colors";
import helmet from "helmet";
import path from "path";
import { fileURLToPath } from "url";
import bodyParser from "body-parser";
import { sequelize as creator } from "./sql/creator.js";
import sequelize from "./sql/conection.js";
import {router as routes_create} from "./routes/router.js"

const app = express();
const __fileName = fileURLToPath(import.meta.url);
export const __dirName = path.dirname(__fileName);


//CORS
const whitelist = [];
const corsOptions = {
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
            callback(null, true);
        } else {
            callback(new Error("Not allowed by CORS"));
        }
    },
};
//CORS

//APP CONFIG

app.use(express.static(__dirName + '/public'));
app.use(helmet());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(
  cors({
    credentials: true,
    origin: whitelist,
  })
);

app.use(routes_create)

I don't know why the only response I get from the console.log(req.body) is {}

Thanks for the help.

0

There are 0 answers