AJAX POST not sending request to express.js server with body-parser due CORS problem (SOLVED)

I’m trying to make an AJAX POST request from my html page which runs on an apache server. The request is needed to POST a filename to the express.js server and do some stuff with it with another node. I also installed the body-parser node.

What am I missing? The server works fine and when I test it in the browser it will return some info. My node express server does not seem to recieve my ajax call. I’ve been reading and trying several posts on this subject on this website for days now.

my code in the scripts part of my html page

function ImportFIT() {
    
    var data = {"fname":"test"};
    
    $.ajax({
        url: 'http://localhost:8000/FileName',
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify(data),                 
        success: function(result) {
            alert('success');
            
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
             alert("error");
        }
    });
}

And the code in node.js

var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');

const port = 8000

app.use(bodyParser.json()); 

app.post('/FileName', function (req, res) {

    console.log(req.body.fname);
    
})
  
app.listen(port, () => {
      console.log(`FIT app listening at http://localhost:${port}`)
    })

106 thoughts on “AJAX POST not sending request to express.js server with body-parser due CORS problem (SOLVED)”

Leave a Comment