0

I'm working on a project where APIs are needed, and more exactly, the POST method. I've read a Stack overflow's thread on it but it doesn't helped a lot : they just said to Use Access-Control-Allow-Origin although I've already done that.
So, here there is the Frontend's side :

const CHEMIN_AU_SERVEUR = "http://localhost:3000/api/stuff";

const func_that_post_the_card_created = (path, json) => {
    const request_projets_post = new XMLHttpRequest();
    request_projets_post.open("POST", path, true);
    request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request_projets_post.send(JSON.stringify(json));
};

func_that_post_the_card_created(CHEMIN_AU_SERVEUR, "title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href");

And here the server side
server.js

const http = require('http');
const app = require('./app');

app.set('port', process.env.PORT || 3000);
console.log(process.env.PORT || 3000);
const server = http.createServer(app);

server.listen(process.env.PORT || 3000);

app.js

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const ProjectScheme = require("./models/Project");
const mongoose = require("mongoose");

// The mongoose connect that will not show

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  next();
});

app.use(bodyParser.json());
app.post("/api/stuff", (req, res, next) => {
  const projet = new ProjectScheme({ ...req.body });

  projet.save()
    .then(() => res.status(201).json({ message: "Projet enregistré !" }))
    .catch((error) => res.status(400).json({ error }));
});

And finally /models/Project.js

const mongoose = require("mongoose");

const ProjectScheme = mongoose.Schema({
    title: { type:String, required:true },
    description: { type:String, required:true },
    imageUrl: { type:String, required:true },
    href: { type:String, required:true },
    github_href: { type:String, required:true },
});

module.exports = mongoose.model('Projet', ProjectScheme);

Thanks for helping. It will be very helpful. I think it will help also a lot of other people.

1 Answers1

2

The problem is here:

request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request_projets_post.send(JSON.stringify(json));

In the first row, you set the content type as application/x-www-form-urlencoded. In the second, your body is a JSON string.

The data you are sending to the function is urlencoded:

title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href

But on your server you parse the body as json:

app.use(bodyParser.json());

You can't mix the encoding. You need to decide whether you want to use JSON or urlencoded:

JSON

In your frontend:

request_projets_post.setRequestHeader("Content-type", "application/json");
request_projets_post.send(JSON.stringify(json));

And the data you provide to the function is is an object:

func_that_post_the_card_created(CHEMIN_AU_SERVEUR, {
  title: title,
  description: description,
  imageUrl: imageUrl,
  href: href,
  github_href: github_href
});

No changes required in the backend

URLENCODED

Do not use JSON.stringify:

const func_that_post_the_card_created = (path, data) => {
    const request_projets_post = new XMLHttpRequest();
    request_projets_post.open("POST", path, true);
    request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request_projets_post.send(data);
};

func_that_post_the_card_created(CHEMIN_AU_SERVEUR, "title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href")

In your server remove the line

app.use(bodyParser.json());

and add:

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

See: How can I read the data received in application/x-www-form-urlencoded format on Node server?

gbalduzzi
  • 9,356
  • 28
  • 58