I followed the node http document to write a delete request to the local server, but receive the socket hang up error, similar question I checked are:
NodeJS - What does “socket hang up” actually mean?
Error: socket hang up using node v0.12.0
but no one actually work for my scenario.
I believe it is the code error because I use postman it works for me, following is my code
var options = {
hostname: 'localhost',
port: 3000,
path: '/accounts/abc'
method: 'DELETE',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
};
var order = {
"secret": "abc_secret"
};
var content = JSON.stringify(order);
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
res.on('data', function(chunk) {
console.log('resp: ' + chunk);
});
});
req.on('error', function(err) {
console.error('error: ' , err.stack.split("\n"));
});
req.write(content);
req.end();
and the errors are:
error: [ 'Error: socket hang up',
' at createHangUpError (_http_client.js:215:15)',
' at TLSSocket.socketOnEnd (_http_client.js:300:23)',
' at TLSSocket.emit (events.js:129:20)',
' at _stream_readable.js:908:16',
' at process._tickCallback (node.js:355:11)' ]
Apparently, the request header does not have content length. Therefore, whatever you wrote in the write function will be ignored. Hope this is the root cause.
for me - solved by add Content-Length header.
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(JSON.stringify(order))
}
Related
I am running buildroot and iotjs on an iot device and I'm trying to make a post request to login and get an auth token. But I'm unable to call the API at all because I run into an error that says
"API Failed, problem with request: handshake failed: domian"
The same API works given I use the http version. The server I'm trying to call is hosted on an AWS EC2 instance behind cloudflare.
The code (not exactly the same but similar) used to call the API:
var https = require('https');
var options = {
host: 'www.google.com',
port: 443,
path: '/upload',
method: 'POST'
};
var req = https.request(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('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Any help is appreciated thanks!
I'm trying to load weather data. I have front end code that was doing this perfectly but I need to move this to back end. I moved a library of my functions over to Node.JS. I was using $.getJSON but was told I should use https.request for the new version. Here's my code:
getTextWeatherUsingStationUsingRequest: function(theStation){
const http = require("http");
const https = require("https");
thePath = 'stations/' + theStation + '/observations/current';
// theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current';
function requestTheData(){
var options = {
protocol: "https:",
hostname: "https://api.weather.gov/",
path: thePath,
port: 80,
method: "GET"
};
var instaRequest = https.request(options);
instaRequest.on("response", function(res){
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
console.log("response");
console.log(res.statusCode);
console.log(res.statusMessage);
});
instaRequest.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
instaRequest.end();
}
requestTheData();
I'm getting this error and can't figure out what's going on:
problem with request: getaddrinfo ENOTFOUND https://api.weather.gov/stations/ https://api.weather.gov/stations/:80
HTTPS generally uses port 443, so lets change that. Also, the API shows the hostname should be the raw URL and the path should be the remainder of the route (with a leading slash) similar to this:
thePath = '/stations/' + theStation + '/observations/current';
...
var options = {
hostname: "api.weather.gov",
path: thePath,
port: 443,
method: "GET"
};
Before even seeing any answers I got it working by:
protocol: "https:",
hostname: "api.weather.gov",
but then I was getting a STATUS:
403 Forbidden You don't have permission to access
"http://api.weather.gov/" on this server.
I seemed to remember that you are required to pass something in through headers so I added this under "method: "GET","
method: "GET",
headers: {
'Accept' : 'application/json',
'Content-Type': 'application/json',
'User-Agent' : 'MY-UA-STRING'
}
And, voila, now I'm getting JSON weather data. It didn't work until I added the 'User-Agent'. Do you guys know what this needs to be (and/or point me to a place that describes this)?
I recently got myself an esp8266-12e module and loaded the ESPRUINO.js firmware on it. I am trying execute a post request from the device, but the device always returns a 'no connection' error when trying to POST.
To troubleshoot I have ran a GET request to the same URL, and the request was successful, this means that internet is working on the device and communication with the intended server is possible.
I then moved on to see if there were errors in my HTTP POST code, I ran the same code in a node.js app and it successfully posted to the server.
Here is the code below, I removed the exact address of my server and my wifi/pass info.
var http = require("http");
var wifi = require("Wifi");
var sdata = {
deviceID: 'esp-12',
};
var options = {
hostname: 'immense-XXXXXX-XXXXX.herokuapp.com',
method: 'POST',
path:'/MXXXXXX',
headers: {
'Content-Type': 'application/json'
}
};
var req = http.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(body) {
console.log('Body: ' + body);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
payload = JSON.stringify(sdata);
req.write(payload);
req.end();
terminal response from device after execution
problem with request: no connection
Here is the documentation for Espruino.js HTTP module.
https://www.espruino.com/Reference#http
Can any of the JS gurus see an issue with the request?
Turns out the http post request requires the 'content-length' header to function correctly.
Here is the working post request model for anyone who may need it. Note: Payload has already been formatted as a JSON object.
function postX(payload) {
var options = {
host: 'url',
port: '80',
path:'/ext',
method:'POST',
headers: { "Content-Type":"application/json", "Content-Length":payload.length }
};
var req = require("http").request(options, function(res) {
res.on('data', function(data) {
console.log("-->"+data);
});
res.on('close', function(data) {
console.log("==> Closed.");
ticksSinceConnect = 0;
});
});
req.end(payload);}
I have a command-line script written in JavaScript which needs to connect to a REST Api on a remote SharePoint site, but I cannot figure out how to authenticate. I can log on in a browser using forms authentication, and by inspecting the request I should be able to reproduce it in node.js to get the appropriate auth cookie or token. However, I actually get a 403 Forbidden. I don't know if this is the best way of doing it, but I can't find very much info on it. Here is my script:
var http = require('http');
var querystring = require('querystring');
var postData = querystring.stringify({
'ctl00$PlaceHolderMain$signInControl$UserName': 'restapi',
'ctl00$PlaceHolderMain$signInControl$password': 'my_password',
'ctl00$PlaceHolderMain$signInControl$login': 'Sign In'
});
var options = {
hostname: 'sharepoint.example.com',
port: 80,
path: '/_layouts/15/Authenticate.aspx?Source=%2F',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ', res.headers);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
And the response headers are:
{ 'cache-control': 'private',
'content-type': 'text/plain; charset=utf-8',
server: 'Microsoft-IIS/8.5',
'x-sharepointhealthscore': '0',
'x-aspnet-version': '4.0.30319',
sprequestguid: '366d149d-79af-b07c-1764-dec7001b46a2',
'request-id': '366d149d-79af-b07c-1764-dec7001b46a2',
'x-frame-options': 'SAMEORIGIN',
sprequestduration: '7',
spiislatency: '0',
'x-forms_based_auth_required': 'http://sharepoint.example.com/_login/default.aspx?ReturnUrl=/_layouts/15/error.aspx&Source=%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F',
'x-forms_based_auth_return_url': 'http://sharepoint.example.com/_layouts/15/error.aspx',
'x-msdavext_error': '917656; Access denied. Before opening files in this location, you must first browse to the web site and select the option to login automatically.',
'x-powered-by': 'ASP.NET',
microsoftsharepointteamservices: '15.0.0.4569',
'x-content-type-options': 'nosniff',
'x-ms-invokeapp': '1; RequireReadOnly',
date: 'Sat, 27 Jun 2015 10:53:28 GMT',
connection: 'close',
'content-length': '13' }
Any suggestions?
Are you sure that REST API allows CORS? because a 403 Forbidden might mean that you are not allowed to contact that endpoint from outside.
Does that remote SharePoint app use AD for authentication?
if so you might need to check this package https://www.npmjs.com/package/activedirectory
A couple of months back,the code below worked perfectly and was used to add a new document in couchdb (iriscouch).
Now I'm getting a HTTP Status 500. Is there a workaround?
Code (in Node.js) :
var http=require('http');
var options = {
host: 'sbose78.iriscouch.com',
path: '/bosedb1',
method: 'POST',
headers:{
'Content-Type':'application/json',
'accept':'application/json'
}
};
var data={
'servings' : 4,
'subtitle' : "Delicious with fresh bread",
'title' : "Fish Stew------"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
var body="";
res.on('data', function (chunk) {
body+=chunk;
console.log('BODY(inside listener):\n ' + body);
});
console.log('BODY (outside listener): ' + body);
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
//write data to request body
req.write(JSON.stringify(data));
req.end();
The response:
STATUS: 500
HEADERS: {"content-type":"text/plain","content-length":"239"}
BODY(inside listener):
Internal routing error
Sorry, we cannot connect to the intended server.
We have just been notified of this problem. We will correct it as soon as possible.
Feel free to contact us if you have any questions: support#iriscouch.com
Looks like http://www.iriscouch.com/ is down at the moment:
Host not found: www.iriscouch.com
Have you considered using an abstraction layer, at least to do http?
request
Your codebase is going to have a lot of http code if you don't :)
Personally I wrote and maintain the node.js CouchDB client which is based on request, if you are curious about it you can find out more at github