I am attempting to send a rest request over https using the following
// Construct the POST auth body and options
let postData = JSON.stringify({
username: this.state.username,
password: this.state.password
});
console.log(postData);
var options = {
host: this.state.peerAddress,
port: this.state.port,
path: "/api/" + this.state.channelName + "/user-authorisation",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": postData.length
}
};
console.log(options);
var postRequest = https.request(options, function(res) {
console.log("\nstatus code: ", res.statusCode);
res.setEncoding("utf8");
res.on("data", function(data) {
console.log(JSON.parse(data));
});
});
e.preventDefault();
// post the data
postRequest.write(postData);
postRequest.end();
The request is sent to the server but there is no body present. I have tested this by sending the same request over postman and it works fine. I am sending the request on Chrome if that makes any difference? I get the following errors on the console but these happen after the request has been sent I believe so that are not really an issue at this point.
request.js:149 OPTIONS https://<<address>>:<<port>><<path>> net::ERR_CONNECTION_REFUSED
localhost/:1 Uncaught (in promise) TypeError: Failed to fetch
Any help would be greatly appreciated!
Cheers
Hello and happy new year!
I'm trying to send a post petition in Node.js. The version I need to replicate in javascript looks like this:
$.post('website.com/api/buy.php', {
action: order,
'items[]': cart_i,
time: localtime,
utb: x //I don't know why that parameter is sent. It's always 0 ._.
} ... //rest of the code of that website
I'm trying to do this in Node.js to replicate that:
var postData = querystring.stringify({
action: 'order',
"items[]": item.i,
time: local_time,
utb: 0
});
var https = require('https');
var options = { method: 'POST', host: 'website.com', port: 443, path: '/api/buy.php', headers: { 'Cache-Control': 'no-cache', 'Cookie': cookies, 'Accept': '/', 'Connection': 'keep-alive' } };
var req = https.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
content = content+ chunk;
});
res.on('end', function () {
console.log(content)
});
}
);
req.write(postData);
req.end();
But I always get an error telling me that I didnt send anything. I think the problem could be in items[] because I see it sends "items%5B%5D", but I dont know if I'm doing something wrong. I think is is not about cookies, because if I'm not logged I get other error.
I'm doing the request well? Or I'm missing something that is not about the request? Is there other way to send "post" data easier?
Any help would be appreciated :)
Ultimately I am just trying to POST an image from the browser to a server. Unfortunately running into CORS issues, so for the moment, attempting to use our Node.js server as a proxy server.
I have this:
router.post('/image', function (req, res, next) {
const filename = uuid.v4();
const proxy = http.request({
method: 'PUT',
hostname: 'engci-maven.nabisco.com',
path: `/artifactory/cdt-repo/folder/${filename}`,
headers: {
'Authorization': 'Basic ' + Buffer.from('foo:bar').toString('base64'),
}
});
req.pipe(proxy).pipe(res).once('error', next);
});
the browser initiates the request, but I get an error in the browser saying I get an empty response, the error is:
Does anyone know why this error might occur? Is there something wrong with my proxy code in Node.js? Authorization should be fine, and the requeset url should be fine. Not sure what's going on.
Ok so this worked, but I am not really sure why:
router.post('/image', function (req, res, next) {
const filename = uuid.v4();
const proxy = http.request({
method: 'PUT',
hostname: 'engci-maven.nabisco.com',
path: `/artifactory/cdt-repo/folder/${filename}`,
headers: {
'Authorization': 'Basic ' + Buffer.from('foo:bar').toString('base64'),
}
}, function(resp){
resp.pipe(res).once('error', next);
});
req.pipe(proxy).once('error', next);
});
There is an explanation for why this works on this Node.js help thread:
https://github.com/nodejs/help/issues/760
Using API auth
var oauth2 = new OAuth2('Consumer Key', 'Consumer Secret', 'https://api.twitter.com/', null, 'oauth2/token', null);
oauth2.getOAuthAccessToken('', 'grant_type': 'client_credentials' }, function (e, access_token) {
console.log(access_token); //string that we can use to authenticate request
requestURL = {
url: 'https://api.twitter.com/1.1/statuses/user_timeline?user_id=' + userid,
headers: {
Authorization: 'Bearer ' + access_token
}
};
request(URL, function(error, response, body){
console.log(request);
console.log(body); }
With this code I am getting 403 Forbidden but with the same code on other APIs e.g search/tweets it works fine.
What am I missing here ?
And no, the user is not private.
You have got an error on the called URL. It should be:
...
url: 'https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=' + userid,
...
I am trying to post some json to a URL. I saw various other questions about this on stackoverflow but none of them seemed to be clear or work. This is how far I got, I modified the example on the api docs:
var http = require('http');
var google = http.createClient(80, 'server');
var request = google.request('POST', '/get_stuff',
{'host': 'sever', 'content-type': 'application/json'});
request.write(JSON.stringify(some_json),encoding='utf8'); //possibly need to escape as well?
request.end();
request.on('response', function (response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
When I post this to the server I get an error telling me that it's not of the json format or that it's not utf8, which they should be. I tried to pull the request url but it is null. I am just starting with nodejs so please be nice.
The issue is that you are setting Content-Type in the wrong place. It is part of the request headers, which have their own key in the options object, the first parameter of the request() method. Here's an implementation using ClientRequest() for a one-time transaction (you can keep createClient() if you need to make multiple connections to the same server):
var http = require('http')
var body = JSON.stringify({
foo: "bar"
})
var request = new http.ClientRequest({
hostname: "SERVER_NAME",
port: 80,
path: "/get_stuff",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})
request.end(body)
The rest of the code in the question is correct (request.on() and below).
Jammus got this right. If the Content-Length header is not set, then the body will contain some kind of length at the start and a 0 at the end.
So when I was sending from Node:
{"email":"joe#bloggs.com","passwd":"123456"}
my rails server was receiving:
"2b {"email":"joe#bloggs.com","passwd":"123456"} 0 "
Rails didn't understand the 2b, so it wouldn't interpret the results.
So, for passing params via JSON, set the Content-Type to application/json, and always give the Content-Length.
To send JSON as POST to an external API with NodeJS... (and "http" module)
var http = require('http');
var post_req = null,
post_data = '{"login":"toto","password":"okay","duration":"9999"}';
var post_options = {
hostname: '192.168.1.1',
port : '8080',
path : '/web/authenticate',
method : 'POST',
headers : {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Content-Length': post_data.length
}
};
post_req = http.request(post_options, function (res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ', chunk);
});
});
post_req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
post_req.write(post_data);
post_req.end();
There is a very good library that support sending POST request in Nodejs:
Link: https://github.com/mikeal/request
Sample code:
var request = require('request');
//test data
var USER_DATA = {
"email": "email#mail.com",
"password": "a075d17f3d453073853f813838c15b8023b8c487038436354fe599c3942e1f95"
}
var options = {
method: 'POST',
url: 'URL:PORT/PATH',
headers: {
'Content-Type': 'application/json'
},
json: USER_DATA
};
function callback(error, response, body) {
if (!error) {
var info = JSON.parse(JSON.stringify(body));
console.log(info);
}
else {
console.log('Error happened: '+ error);
}
}
//send request
request(options, callback);
Try including the content length.
var body = JSON.stringify(some_json);
var request = google.request('POST', '/get_stuff', {
host: 'server',
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'application/json'
});
request.write(body);
request.end();
This might not solve your problem, but javascript doesn't support named arguments, so where you say:
request.write(JSON.stringify(some_json),encoding='utf8');
You should be saying:
request.write(JSON.stringify(some_json),'utf8');
The encoding= is assigning to a global variable, so it's valid syntax but probably not doing what you intend.
Probably non-existent at the time this question was asked, you could use nowadays a higher level library for handling http requests, such as https://github.com/mikeal/request. Node's built-in http module is too low level for beginners to start with.
Mikeal's request module has built-in support for directly handling JSON (see the documentation, especially https://github.com/mikeal/request#requestoptions-callback).
var request = google.request(
'POST',
'/get_stuff',
{
'host': 'sever',
**'headers'**:
{
'content-type': 'application/json'
}
}
);