I have this code in my node backend server:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
And this is the api i.e. i want to call:
router.post('/update/:_id', function(req, res, next) {
console.log("req.body:" + req.body);
}
This is my post request through angular 1:
var data = {something: "something"}
var url = 'http://localhost:8081/update/5982168b399ccf32ad75ce2e';
$http({
withCredentials: false,
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
})
.then(function (response) {
if (response.data) {
console.log("Post Data Submitted Successfully!");
}
}, function (response) {
console.log("Error status: " + response.status)
});
I am using Angular 1.6.1 version.
I have tried everything and looked through countless posts but none helped me. I can see the body going through. But i got undefined req.body in the node side backend.
Any help would be appreciated.
Thanks.
it could be the
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
your data is in JSON format, not x-www-form-urlencoded
{something: "something"}
you could try this
headers: {'Content-Type': 'application/json'}
by default you send JSON data in $http POST, so you may not need the header
just take it out and try
===============================================================
also, your data may not be in valid format
JS does not know what something is, it's not a variable right?
you have to make it a string, even if its the key of a { "key": "value" } pair
you could try this if above doesn't work
{
"something": "something"
}
to verify your JSON
https://jsonlint.com/
You need to stringify the data, and change the content type as was already said:
var data = {something: "something"}
var url = 'http://localhost:8081/update/5982168b399ccf32ad75ce2e';
$http({
withCredentials: false,
method: 'POST',
url: url,
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(data)
})
You should in addition make sure that you can make a POST to that url using Postman and that the body is received to discart a problem in the server. On a side note, consider using Angular Resource.
Related
whats up!
i am trying to send a request with json parameters and i don't understand why in the server side
the parameter doesn't being send
let res = fetch("http://localhost:1000/vacations/" + vacation.id, {
method: "DELETE",
headers: { "Authorization": localStorage.token },
body: { "picture": vacation.picture }
})
i am trying to view the picture in the parameter in the server side
i use in node.js server the middleware express.json
and still i cant get this parameter :(
You may send a stringify body using JSON.stringify.
const res = fetch(`http://localhost:1000/vacations/${vacation.id}`, {
method: "DELETE",
headers: {
Authorization: localStorage.token
},
body: JSON.stringify({
picture: vacation.picture
})
})
I mean, i'm trying to make the most simple upload ever, with the following code:
var http = require('http');
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});
The point is, if i make a post like this, what it'll post exacly?
Does i need to put at least one header parameter or this create some kind of template?
If i need to put at least one parameter, i would put it into the form.getHeaders"()"?
Through headers you should send HTTP headers of the request as an object
Example code:
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: {
'Accept': 'text/html',
}
});
full list of the header can be found here
You can send data as JSON with the request as follows:
const data = JSON.stringify({
text: 'Hello World'
});
request.write(data);
request.end();
I am trying to send data through axios request to my backend script, but the body looks empty.
Here's a request sent from front-end:
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
}).then((res)=>{
console.log("api call sucessfull",res);
}).catch((err)=>{
console.log("api call unsucessfull",err);
this.props.toggleLoading(false);
})
Here's a back-end:
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.body);
})
But I am getting {} empty body. I am getting headers and other data but not data.
GET requests should not have a body.
Change the method from 'GET' to 'POST'
Like so:
axios.request({
method: 'POST',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
})
and change your api to expect a post
app.post('/next/api', verifyToken, function(req, res) {
console.log(req.body);
});
or
Change the data property to params
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
params: {
next_swastik: 'lets add something here'
},
})
and change the api to log out the params
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});
and like #MaieonBrix said, make sure that your headers contain the content type that you are sending.
It looks like you only have two points left to make it work :
one : the http method should be set to POST instead of GET since you want to send something.
two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`
On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.
I suppose your server is using express, here is how you will do it with express :
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */
If you get an error that "bodyParser is deprecated", try this -
app.use(express.json()); //To parse JSON bodies (Applicable for Express 4.16+)
And use "post" method, if you want to get data from body of the HTTP request.
Try this
this.axios('realties', { params: this.filter })
I'm sending data in my React component via the Fetch API, and returning the result as JSON. When POSTED on my Express server, I use the jsonParser method from bodyParser to parse through the data, but insead I'm only getting back a empty object. I do not understand what's the issue with jsonParser, because if I use textParser, my data get sent fine.
Edit: When printing out the request (req) on the server, it is showing that nothing was received in the body. This only happens with jsonParser though, and not textParser.
Fetch:
fetch('./test',{
method: 'POST',
body: ["{'name':'Justin'}"]
})
.then((result) => {
return result.json();
})
.then((response) => {
console.log(response);
})
.catch(function(error){
//window.location = "./logout";
console.log(error);
});
Express:
app.use('/test', jsonParser, (req,res) =>{
res.json(req.body);
})
Assuming you want to post the {name: 'Justin'} object, you'll want something like
fetch('test', {
method: 'POST',
body: JSON.stringify({name: 'Justin'}),
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8'
})
})
The body parameter does not accept an array (which is what you were passing).
If you did mean to post an array, simply change the body value to
JSON.stringify([{name: 'Justin'}])
Question: What object is the JSON parsed to?
I'm successfully sending a JSON string to the server, but I haven't been able to access the object.
Client script, sending the JSON:
var loginCredentials= {
"username":creds.username,
"password":creds.password };
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
dataType: "json"
});
Login listener, waiting for and supposedly parsing the JSON:
function listen(){
app.use(express.bodyParser());
app.post('/login', function(req, res) {
var util = require('util');
console.log(util.inspect(req.body, false, null));
console.log(req.body.username);
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
Which logs:
Server running at http://127.0.0.1:8080/
{ '{"username":"username1","password":"badpassword"}': '' }
undefined
So it looks like my JSON is parsed right, but I'm trying to access it via req.body.username and it isn't stored there.
The bodyParser doesn't know that you're sending JSON. It assumes the body to be standard www-form-urlencoded, and therefore parses all of it as a single key.
Instead, send the proper content-type with your request:
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
contentType : 'application/json',
dataType: "json" // response type
});
However, as mentioned in Do Not Use bodyParser with Express.js, you might just use the express.json() middleware only.