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.