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.

5
  • 1
    And the question/problem is? -> How do I ask a good question? Commented Oct 30, 2020 at 13:44
  • 1
    What error do you have in the browser console? Commented Oct 30, 2020 at 13:44
  • Ah sorry: the question is why I always get that response from the frontend : POST localhost:3000/api/stuff 400 (Bad Request) Commented Oct 30, 2020 at 13:45
  • Ah yes thanks. Sorry, I had to have checked it. Now Im sure. Commented Oct 30, 2020 at 13:52
  • In your route, the first thing you should do is console.log(req.body);. Just make sure your variables actually contain what you think they contain. Commented Oct 30, 2020 at 13:55

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, very much. Truly. You helped me a lot. Such a joy to see something working !!!!
Do you know much about Mongoose to explain me how to clear an Mongoose Api ?
No, I don't know Mongoose

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.