HTTP post header is incorrect - javascript

I am using node.js to send HTTP POST to an APP server. The email address joe#gmail.com in POST body shows up as joe%40gmail.com on APP server side. I used Content-Type text/plain in the following code but application/x-www-form-urlencoded is actually in the POST request header, according to the server log.
My earlier post has a mistake on Chrome postman results. Please ignore it, and sorry for the confusion.
I am new to this, and may have missed something obvious here. Any help is appreciated.
Here is the code:
var express = require("express");
var app = module.exports = express();
var request = require('request');
var config = require('../config');
app.post('/', function(req, res) {
var username = req.body.name;
var password = req.body.passwd;
var email = req.body.email;
console.log("email=", email);
// connect to APP server
var url = config.appServer;
request( {
uri: url,
method: "POST",
timeout: 10000, // 10 sec
headers: {
'Content-Type': 'text/plain'
},
form: {
act: 'create',
username : username,
passwd: password,
email: email
}
}, function (error, response, body) {
// handle return here

That's completely normal behavior. Also you don't need to set the content-type header when using the form option with request.
Here is a short example:
request({
uri: 'http://requestb.in/1g2xzno1',
method: 'POST',
timeout: 10000, // 10 sec
form: {
act: 'create',
username : 'username',
passwd: 'password',
email: 'joe#gmail.com'
}
}, function (err, res, body) {
if (err) console.log(err)
console.log(body)
})
You can see the results from that request here. This is what your app server receives. Then all you need to do is parse the request body on your app server (it's the string below the RAW BODY header):
var qs = require('qs')
qs.parse('act=create&username=username&passwd=password&email=joe%40gmail.com')
{ act: 'create',
username: 'username',
passwd: 'password',
email: 'joe#gmail.com' }
Alternatively if you are using Express on your app server you can use the body-parser middleware that will do the same for you:
app.use(bodyParser.urlencoded({extended: true}))

Related

When using a fetch request in a Node JS server it receives the body as blank

I was working on a user login system in Node JS and was making a POST request to the server like this.
let data = {
username: "John Doe",
password: "123abc",
}
let options = {
method: 'POST',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data),
}
fetch('/verify-login', options).then(function(r) {
return r.text();
}).then(function(dat) {
if (dat == 'n') {
document.getElementById('login-fail').innerHTML = 'User name or password is incorrect!';
} else {
console.log('Login Success');
}
});
Server Side code:
const express = require('express');
const port = 80;
const bodyParser = require("body-parser");
const fs = require('fs');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
const cors = require("cors");
app.use(cors());
app.post('/verify-login', async function(q, r) {
let dat = await q.body; //<-- Body is just {} not what the fetch request sent
//do account check stuff with dat
if (success) {
r.send('y');
} else {
r.send('n');
}
});
app.listen(port, function() {
console.log("Started application on port %d", port);
});
This issue is that on the server side when I receive the request, the body is returned with '{}'. Does anybody know why this is happening and how I can fix it?
There are various data types you can pass to fetch through the body option.
If you pass something it doesn't recognise, it converts it to a string and sends that.
Converting a plain object to a string doesn't give you anything useful.
let data = {
username: "John Doe",
password: "123abc",
}
console.log(`${data}`);
You said you were sending JSON (with the Content-Type header. So you need to actually send JSON.
const json = JSON.stringify(data);

Can't get data from client on server-side with Ionic and Express.js

This question might have been ansked before, but i can't seem to find the correct answer for it. I'm working on a Ionic project where i've created another project with Node.js and express.js to handle all my http requests. Both are running on localhost at the moment. When i'm trying to send some data from my client-side to to server-side, the data that i'm getting from the request looks like this when i console.log(req.body):
{ '{"username":"hello#hello.com"}': '' }
I tryed both req.body[username] and so on to get the data, but then it just gets undefined.
My controller for handling the http request looks like this:
$scope.submit = function(){
var username = $scope.username;
console.log($scope.data.username);
$http({
method: 'POST',
url: 'http://localhost:8000/api/users',
data: username,
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}
});
Html element
<input type="text" ng-model="data.username" name="name">
Server-side API looks like this:
router.post('/users', function (req, res) {
var username = req.body;
var newUser = new User({
username: username
})
newUser.save(function (err) {
if (err) {
return res.send(500, err);
}
return res.json(200, newUser);
});
});
Server.js bodyparser included
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
Object have keys and values
{ key: value }
The object on the body is beeing sent in some wrong way since you're sending a object with they key '{"username":"hello#hello.com"}' which has the value ''.
I would recomend fixing how you're posting to your nodejs/express server. But you can get the value by some hacks. Like this.
const body = {'{"username":"hello#hello.com"}': '' }
const keys = Object.keys(body);
const parsed = JSON.parse(keys[0]);
console.log(parsed.username);
https://jsfiddle.net/wejh0fsk/2/
Edit: So what I am doing here is getting all the keys of the object. There's only one key '{"username":"hello#hello.com"}'. Since that key is a string I am parsing it to get a object. Now I have a object
{ username: 'hello#hello.com' }
And finally I'm logging out the username.
The right solution would to fix how your sending your data to the express server.
I don't quite understand your controller. Your ng-model is data.username but then you're putting
var username = $scope.username
Which should be
var username = $scope.data.username // (that's at least what you're binding to in your view)
Also you want to send an object with the post, not just the value
$scope.submit = function(){
var username = $scope.username;
console.log($scope.data.username);
$http({
method: 'POST',
url: 'http://localhost:8000/api/users',
data: { username: username },
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}
});
I am not sure on express parsers but I don't know why you're calling the bodyparser twice. The first one should be enough.

Get token oAuth using npm

I'm trying to develop a service using nodeJS that retrieve a token OAuth from a server. But I have every time an error.
this the function.
var express = require('express')
var http = require('http');
var httpRequest = require('request');
var bodyParser = require('body-parser');
var app = express()
app.get('/get-token', function (request, response) {
// Ask for token
httpRequest({
url: 'https://my-server.com/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic SdfdhffhPeHVBTV84OExfVWFmR1cwMklh'
},
form: {
'grant_type': 'password',
'username': 'myLogin',
'password': 'myPwd',
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
});
When I make a request, the server return this error:
{ [Error: unable to verify the first certificate] code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' }
Would you have an idea how I can process or if there is a package npm that make the same job ?
Best regards
This wokrks for me
...
app.get('/get-token', function (request, response) {
// Ask for token
httpRequest({
rejectUnauthorized: false,
url: 'https://my-server.com/token',
...

How to pass json to nodejs request post method?

I try to pass json to nodejs post method.But i'm getting error "The search query must be specified.". I have specified search string and filter the code. Can you advise what cause this error.
Same request working in POSTMAN.
//Load the request module
var express = require('express');
var request = require('request');
var app = express();
//Lets configure and request
request({
url: 'http://host:8080/rest/1.0/search',
qs: {query: 'nodejs*'},
method: 'POST',
json: {
filter:
{
community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
type: {asset:['00000000-0000-0000-0000-000000011001']},
},
fields: ['name']
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
app.listen(8080);
As per your postman screenshot you can try the below code by getting rid of qs: {query: 'nodejs*'} and adding the same inside the json.
//Load the request module
var express = require('express');
var request = require('request');
var app = express();
//Lets configure and request
request({
url: 'http://host:8080/rest/1.0/search',
method: 'POST',
json: {
query: 'nodejs*',
filter:
{
community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
type: {asset:['00000000-0000-0000-0000-000000011001']},
},
fields: ['name']
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
app.listen(8080);

Unexpected token - while parsing json request

I have two node servers and I am trying to send files between them using a rest api. However when I am sending the data I get a "Unexpected token -"on the receiving server. On the sender I get an [Error: write after end].
My router code:
var express = require('express');
var multer = require('multer');
var path = require('path');
var Router = express.Router;
const MODULES_PACKAGES_UPLOAD_DIR = path.resolve('/tmp');
module.exports = function() {
var router = new Router();
var storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, MODULES_PACKAGES_UPLOAD_DIR);
}
});
var upload = multer({storage: storage});
router.post('/fileUpload', upload.array(), function(req, res){
debug('We have a a file');
//Send the ok response
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('\n');
}
The sending code:
var Util = require('util');
var http = require('request-promise');
var request = require('request');
var fs = require('fs');
var Post = require('http');
var FormData = require('form-data');
//Generate the form data
var formdata = modules.map(function(fileName){
return fs.createReadStream('/opt/files/'+fileName);
});
var data = getData(); //Gets the body of the code as a promise
return Promise.all(data)
.then(function(dataResults){
var options = {
method: 'POST',
uri: 'https://' + name +'/file',
rejectUnauthorized: false,
timeout: 2000,
body: {
keys: keyResults,
modules: modules,
},
formData: { <====== If I remove this section everything works
'module-package': formdata,
},
json: true // Automatically stringifies the body to JSON
};
request.post(options, function(err, response){
if( err){
debug('Error: ',err);
}
else{
debug('We posted');
}
});
The weird thing is that if I remove the formData section then everything works but when it is there I get an exception that says:
SyntaxError: Unexpected token -
at parse (/home/.../projects/node_modules/body-parser/lib/types/json.js:83:15)
Does anyone have any idea what I could be doing wrong??
Just in case anyone in the future comes with the same problem. As #Bergi mentioned. You cant have both json data and form data. You need to choose either one. The solution is to just pass the json data as apart of the form like.
var options = {
method: 'POST',
uri: 'https://' + name +'/file',
rejectUnauthorized: false,
timeout: 2000,
body: {
},
formData: {
'module-package': formdata,
keys: keyResults,
modules: modules,
},
json: true // Automatically stringifies the body to JSON
};
request.post(options, function(err, response){
if( err){
debug('Error: ',err);
}
else{
debug('We posted');
}
});
In my case, the header of the HTTP Request contained "Content-Type" as "application/json".
So here are the things to check:
Send only either form-data or json body. NOT BOTH.
Check for Headers if the "Content-Type" is mentioned. Remove that.

Categories