Home > Back-end >  AJAX and Node JS : receiving empty data in my server
AJAX and Node JS : receiving empty data in my server

Time:05-29

I'm trying to make a POST request to my node JS server, I tried with Postman and it's works fine but when I use AJAX I got an empty data in the server, I tried to use contentType: "application/json" but I got this error enter image description here this is AJAX code :

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "http://localhost:3000/comment",
    data: {
        "email": "[email protected]",
        "contenu": "Hello",
        "id_article": 1653817160
    },
    success: function (data2) {
        console.log(data2)
    }
})

CodePudding user response:

Your issue is related to CORS setup on the NodeJS server. Basically your server has this policy that every request needs to be made from the same domain.

Here is explained how CORS works: https://web.dev/cross-origin-resource-sharing/

Be careful, it's important to have this in mind:

WARNING: Using Access-Control-Allow-Origin: * can make your API/website vulnerable to cross-site request forgery (CSRF) attacks. Make certain you understand the risks before using this code.

Install the CORS package from npm or yarn and follow this code sample:

Install the CORS package from npm or yarn and follow this code sample:
  const express = require('express');
const cors = require('cors');
const http = require('http');

require('dotenv').config();

const port = process.env.PORT || 3000;
const app = express();

app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(express.static('views'));
app.use(cors());

Hope it will help you :)

  • Related