when i post json data on node server, it leads to error
'Response to preflight request doest't pass access control check'
but when i post same request on php server it works .
browser console picture
can someone tell me why this not working in node.js but
when i tried to post data through postman on node server now no error it works.
postman picture
here is my nodeJS code
const express = require('express');
const app = express();
app.use(express.json());
app.post('/post', function(req, res){
res.header('Access-Control-Allow-Origin', '*');
res.send(req.body);
})
and this is request code that is send from browser
function callAjax(){
jQuery.ajax({
method: 'POST',
url:'http://localhost:3010/post',
"headers": {
"content-type": "application/json"
},
data: {
email:'fake#mail.com'
},
success: function(data){
console.log(data);
},
error: function(err){
console.log(err);
}
});
}
You have to use body-parser.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/post', function(req, res){
res.setHeader('Access-Control-Allow-Origin', '*');
res.json(req.body);
});
use cors module first:-
npm install --save cors
var cors = require('cors')
app.use(cors())
Related
I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.
Here is the code
node js
var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
frontend
axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))
The response is an empty object.
What should I do?
By default your axios code:
axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))
will send the body of the POST request as JSON. Quoted directly from the axios doc.
By default, axios serializes JavaScript objects to JSON
So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.
app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});
Note, there is no need to separately load the body-parser module as it is built-in to Express.
Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.
These request bodies can be handled by the express.urlencoded() middleware in the same way as express.json().
You should use bodyParser.json(), to get the data sent in req.body.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
We should parse request body before access it using middleware in the following way
app.use(bodyParser.json());
I know there are a lot of answer already marked as a working solution, but I can't make it work in my case, so please don't marked it as already answered, this is my scenario:
AJAX CLIENT SIDE
var data ={};
data.test="ciaozio";
$.ajax({
url: 'http://localhost:5000/dir',
method: "POST",
contentType: "application/json",
data: JSON.stringify(data),
header: "Access-Control-Allow-Origin",
success: function(data){
console.log(data);
},
error: function(data) {
console.log("error");
}
});
NODEJS SERVER-SIDE
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(bodyParser.json()); // support json encoded bodies
app.use('/', router);
app.post('/dir', function (req, res) {
console.log(req.body);
res.end("Ok");
})
var server = app.listen(5000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
CONSOLE-OUTPUT
Example app listening at http://:::5000
{}
CLIENT-SIDE CONSOLE OUTPUT
Access to XMLHttpRequest at 'http://localhost:5000/dir' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index.js:29 error
jquery-3.4.1.min.js:2 POST http://localhost:5000/dir net::ERR_FAILED
You need to add and configure CORS to your request.
Steps:
1.Install cors npm package
npm install cors
2.Node server-side snippt
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
//app.use(...) lines;
// app.post(..) lines;
I using ReactJs build the form for user key in the details. I also using NodeJs to handle the post data from the React. But the NodeJs seem like did not catched the data.
This is react event handling
handleSave(e){
let caseData=this.state.caseInfo
let url = 'http://localhost:8080'
console.log(caseData)
fetch(url,{
method:"POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify({caseInfo: caseData}),
})
}
This is NodeJS
var http = require('http');
var url = require('url');
var bodyParser = require('body-parser')
var express = require('express')
var app = express()
http.createServer(function(req,res){
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(function (req, res){
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
console.log(JSON.stringify(req.body));
})
}).listen(8080);
I expect the data from the React can using post method to the Node and display the data in console log. However in the console of the server it display nothing.
It seems like you're not using express in the standard way. I'd change it to be more like the following...
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);
And probably just get rid of the call to http.createServer altogether.
--
Check out the docs for more routing examples: https://expressjs.com/en/starter/basic-routing.html
If you are serving your react app from another server, for instance localhost:3000 (as used by create react app), and you are trying to make api calls to a server on localhost:8080 you are going to get CORS errors because the browser sees these as two different domains. To get started, you can look at the docs here: https://expressjs.com/en/resources/middleware/cors.html
But you will probably have to npm install cors where your server lives and use something like the following:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);
var express = require('express'); // Express instance to access its
var path = require('path');
var mongoose = require("mongoose"); // mongodb ODM
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000); //
app.use(express.static(path.join(__dirname, 'node_modules')));
mongoose.connect(config.MONGO_DB_URI, function(error){
if (error) {
console.log("Oops! Connection Failed! " + error);
} else {
console.log("Ahoy! Connection Successful with Mongo!");
}
});
app.use('/api', function(req, res){
console.log("dasasasa");
console.log(req.body);
});
module.exports = app;
when I log req.body it is an empty object {}.
Also the version of body parser is:
npm body-parser -v
2.15.9
What can i be missing here?
Also I am trying it with postman.
The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.
Make sure you're using some thing like:
Client.js:
$.ajax({
type: "POST",
url: '/yourRoute',
data: data,
dataType: dataType,
success: function(data) {
//do something
}
});
and server.js
app.use('/yourRoute', function(req, res) {
console.log(req.body) // should be data from client
})
In node express when I try to access the post value from the form it shows request body undefined error.
Here is my code,
http.createServer(function(req, res) {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;
if (pathname==="/login" && req.method ==="POST") {
console.log("request Header==>" + req.body.username );
}).listen(9000, function() {
console.log('http://localhost:9000');
});
Please any one help me to find why the request body shows undefined.
Enable body-parser middleware first
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
If you're not using express for the web server and just plain http. Use the body module.