How to send a Single-Part POST Request in Node.js? - node.js

PhantomJs's webserver does not support multipart requests, so I'm trying to send a single-part request from NodeJs.
Unfortunatly the nodejs example looks to be multipart. is there any way of doing this with NodeJs?
http://nodejs.org/api/http.html#http_http_request_options_callback
edit:
in the nodejs docs it mentions:
Sending a 'Content-length' header will disable the default chunked encoding.
but unfortunatly it's still multi-part, just not multi-multipart :P
edit2: for showing code, it's a bit hard to show a distilled example, but here goes:
node.js code (it's Typescript code):
```
//send our POST body (our clientRequest)
var postBody = "hello";
var options : __node_d_ts.IRequestOptions = {
host: host,
port: port,
path: "/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-length": postBody.length
}
};
//logger.assert(false);
var clientRequest = http.request(options,(response: http.ServerResponse) => {
//callback stuff here
});
clientRequest.on("error", (err) => {
thisObj.abort("error", "error,request error", err);
});
//clientRequest.write();
clientRequest.end(postBody);
```
when i read the results from PhantomJS, the post/postRaw fields are null.
when I use a tool like the Chrome "Advanced REST Client" extension to send a POST body, phantomjs gets it no problem.
i don't have a network sniffer, but as described here, it says phantomjs doesnt work with multipart so I think that's a good guesss: How can I send POST data to a phantomjs script
EDIT3:
indeed, here's the request phantomjs gets from my chrome extension (valid post)
//cookie, userAgent, and Origin headers removed for brevity
{"headers":{"Accept":"*/*","Accept-Encoding":"gzip,deflate,sdch","Accept-Language":"en-US,en;q=0.8,ko;q=0.6","Connection":"keep-alive","Content-Length":"5","Content-Type":"application/json","DNT":"1","Host":"localhost:41338", "httpVersion":"1.1","method":"POST","post":"hello","url":"/"}
and here's the request phantomjs gets from the nodejs code i show above:
//full request, nothing omitted!
{"headers":{"Connection":"keep-alive","Content-Type":"application/json","Content-length":"5","Host":"10.0.10.15:41338"},"httpVersion":"1.1","method":"POST","url":"/"}

Related

getting 403 error while sending file to githib via REST using nodejs

I want to send multiple files to Github repository via nodejs. Tried several approaches and end up using node-rest-client module. Tried below code send a sample file to repository called 'metadata'. But after post I am getting error message "Request forbidden by administrative rules. Please make sure your request has a User-Agent header"...please let me know if anyone faced this error before and get rid of it.
convertval = "somedata";
var dataObj = {
"message": "my commit message",
"committer": {
"name": "Scott Chacon",
"email": "ravindra.devagiri#gmail.com"
},
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}
debugger;
var Client = require('node-rest-client').Client;
var client = new Client()
var args = {
data: dataObj,
headers: { 'Content-Type': 'application/json' },
};
client.post("https://api.github.com/repos/metadata/contents", args, function (data, response) {
console.log("file send: True : " + data);
});
According to the REST API:
All API requests MUST include a valid User-Agent header. Requests with
no User-Agent header will be rejected.
First of all, you need to define 'User-Agent' with value 'request' in your request header. Refer to this link.
Second, endpoint you are trying to call might require authentication. Generate a personal token from here, add that token in your request header, 'Authorization': 'token '.
If you're using Git extensively in your code, I suggest you to use this - Nodegit.
Edit:
I don't think sending multiple files in a single request is possible in 'Contents' endpoints group (link).
You can checkout Git Data API (as discussed here).

NodeJS Soap Client

I've been working on a script that sends and reads data from and to a SOAP server. I've been doing it pretty simple with the requests module. However, this isn't really ideal for me. So, I've decided to try and use the soap module. This is my current code:
var soap = require("soap");
function fetch2(actor) {
var uri = `http://moviestarplanet.com/Webservice/User/UserService.asmx?wsdl`;
soap.createClient(uri, {}, function(err, client) {
client.GetActorIdByName({ actorName: actor }, function(err, result) {
console.log(err, result);
});
});
}
However, this is giving an error and I feel like its because it is important to pass http headers. In my old requests function, I used to pass the following headers
"User-Agent":"Dalvik/1.6.0 (Linux; U; Android 4.4.2; GT-I9505 Build/KOT49H)",
"Content-Length": xmlData.length,
"Content-Type": "text/xml; charset=ISO-8859-1",
So how can I pass http headers with my soap client?
You can add custom header like below
client.addHttpHeader('User-Agent',CustomUserAgent);
For more information: https://www.npmjs.com/package/soap#extra-headers-optional

Node - post xml to server with request

I try to communicate with a REST api via xmls. I generate an xml and test it with Restlet Client (a chrome extenson for testing REST APIs).
It works fine, I receive the response XML.
If I try to send with request-promise, I receive
'<html><head><title>Error</title></head><body>Internal Server Error</body></html>'
in err.response.body.
The response from the API server is always XML, so I do not get why it is 'html'.
Here is the code
options = {
uri: uri,
header: {
'Content-Type': 'application/xml ',
'Accept' : 'application/xml '
},
body: xml // I use the same xml in Restlet Client's body
}
rp.post(options).then(response=>{
console.log('------SUCCESS-----')
console.log(response)
}).catch(err=>{
console.log('------ERROR-----')
console.log(err.response)
})
If you need any plus information, please let me know.

use node.js send request for baidu map API get wrong response?

Im trying to use node.js to send http requst and call baidu map API.
my code in blow:
If you past the url and use browser directly, it will give right response in right format.
But when I use node to send request, I get problem.
var request = require('request');
request(
{ method: 'GET',
uri: 'http://api.map.baidu.com/place/v2/suggestion?query=beijing&region=131&output=json&ak=****hLQKu9ap9fPq5N1ExF1Kk7xe5Eah'
}
, function (error, response, body) {
res.json({
res:response
})
}
)
Meanwhile, if I change the url contains some Chinese like:
http://api.map.baidu.com/place/v2/suggestion?query=北京理工大学&region=北京&output=json&ak=****hLQKu9ap9fPq5N1ExF1Kk7xe5Eah
In node.js it will give status code 400 and totally wrong response.
you must encode your uri with encodeURI
uri: encodeURI('http://api.map.baidu.com/place/v2/suggestion?query=北京理工大学&region=北京&output=json&ak=3104hLQKu9ap9fPq5N1ExF1Kk7xe5Eah')

Making a Post request to Github API for creating issue is not working

I have been trying to make this post request to the github api for the last couple of days, but unfortunately the response is coming back as "bad message"
here is the piece of code we are sending in the post request using https request in node -
This is the post data
var issueData = JSON.stringify({
"title":title,
"body":comment
});
This is the options file
var options = {
host: 'api.github.com',
path: '/repos/sohilpandya/katasohil/issues?access_token='+sessions.token,
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
},
method: 'POST'
};
This is the https request
var requestaddIssue = https.request(options, function(responseFromIssues){
responseFromIssues.setEncoding('utf8');
responseFromIssues.on('data', function(chunk){
console.log('>>>>chunk>>>>>',chunk);
issueBody += chunk;
});
responseFromIssues.on('end',function(issueBody){
console.log(issueBody);
});
});
requestaddIssue.write(issueData);
requestaddIssue.end();
I have tried another approach where the authentication token for the user is in the header as
'Authentication': 'OAuth '+ sessions.token (where we are storing token inside sessions)
But the chunk response always seems to come back with the following in the console log.
{
"message": "Not Found",
"documentation_url": "https://developer.github.com/v3/issues/#create-an-issue"
}
I have tried the same in apigee and it seems to work ok and returns to correct response. Hoping someone can find the minor error in the code above that is causing this bad message error.
Except the issueBody variable is not defined in the snippets you posted, the code is correct. I tried it using a personal access token.
The error you get appears because you need to add a scope with power to open issues.
I tried the repo and public_repo scopes and they are both working. Note that repo has access to private repositories. Here you can see the list of scopes.
If you're using OAuth, then you you should have an url looking like this:
https://github.com/login/oauth/authorize?client_id=<client-id>&scope=public_repo&redirect_uri=<redirect-uri>

Resources