'AJAX POST not sending request to express.js server with body-parser due CORS problem
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}`)
})
Solution 1:[1]
Are you really sure that it isn't a CORS issue?
You aren't handling get requests on the express server, so it could possibly be in a different server/file that cannot access the express server. Inspect with CTRL-SHIFT-I
and look in the console if there are any errors. If there is an error see if it resembles this: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors#identifying_the_issue.
If so then you can disable CORS on your website by changing the NodeJS code to
var express = require('express');
var path = require('path');
var app = express();
var cors = require("cors");
var bodyParser = require('body-parser');
const port = 8000
app.use(bodyParser.json());
app.use(cors());
app.post('/FileName', function(req, res) {
console.log("worked");
console.log(req.body.fname);
res.send();
})
app.listen(port, () => {
console.log(`FIT app listening at http://localhost:${port}`)
})
Install the cors
module accordingly. If you do not see an error similar to the one in the link posted, you might see an error like "$ is not defined" meaning Jquery isn't loaded on your page, or simply the function holding the AJAX request might not be called.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kudos |