request module POST JSON request using Cookies - json

When I am using curl command or Postman I am getting proper response within 1 sec but request module is going into timeout most of the time, pls help.
I think I need to add code for -c cookie.txt -b cookie.txt'
curl https://example.com/cmd -H "Content-Type:application/json" -k -d '{"cmd":{"dlpktenc":{"id":0,"byte0":001,"byte1":532}}} -c cookie.txt -b cookie.txt'
request module:
var request = require('request');
request = request.defaults({jar: true});
request(
{ method: 'POST',
uri: 'https://example.com/login',
form:
{ user: username,
password: password
},
rejectUnauthorized: false,
},
function( err, res, body ){
if (!err){
console.log(JSON.parse(body));
var requestData = {"cmd":{"dlpktenc":{"id":0,"byte0":001,"byte1":532}}};
request(
{ method: 'POST',
uri: 'https://example.com/cmd',
header:{
'content-type': 'application/json',
},
json: requestData,
rejectUnauthorized: false
},
function( err, res, body ){
if (!err){
console.log(body);
} else console.log(err);
});
} else console.log(err);
});

In cURL, -d means (from the man pages, emphasis mine):
-d, --data
(HTTP) Sends the specified data in a POST request to the HTTP server,
in the same way that a browser does when a user has filled in an HTML
form and presses the submit button. This will cause curl to pass the
data to the server using the content-type
application/x-www-form-urlencoded. Compare to -F, --form.
...
See also --data-binary and --data-urlencode and --data-raw. This
option overrides -F, --form and -I, --head and --upload.
If curl is working with the command you said, you need to send your request the same way:
request({
method: 'POST',
uri: 'https://example.com/cmd',
header: {
// Correct content type
'content-type': 'x-www-form-urlencoded',
},
body: requestData,
rejectUnauthorized: false
},
function(err, res, body) {
if (!err) {
console.log(body);
} else console.log(err);
}
);

There is a problem in sending the body in the request module as an object unless the json option is set as true
var requestData = {
"cmd": {
"dlpktenc": {
"id": 0,
"byte0": 001,
"byte1": 532
}
}
};
request({
method: 'POST',
url: 'http://localhost:9007/mbe',
header: {
'content-type': 'application/json',
},
body: requestData,
rejectUnauthorized: false,
//THE NEXT LINE WAS MISSING IN YOUR CODE
json : true
},
function(err, res, body) {
if (!err) {
console.log(body);
} else console.log(err);
}
);

Related

How to enable fetch POST in chrome extension contentScript?

I'm trying to call REST API in chrome extension. I managed to get fetch GET working , but couldn't make POST work. The body on server side is always empty. Here is my fetch request:
let url = "http://localhost:3000/api/save/one"
fetch(url, { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json; charset=utf-8" }, mode: "no-cors", body: JSON.stringify(json) })
.then(resp => console.log(resp))
When I examined the request on server, I did notice that the content-type on server is always "text/plain;charset=UTF-8". So, my headers doesn't seem to be passed over. However, "Accept" header did go through.
This is the headers on server:
accept:"application/json"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"
If I remove "Accept" from my fetch headers, I got this on server:
accept:"*/*"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"
Any explanation on this? So, how to make POST work?
You need to write the code for post method
Listener
background.js:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.contentScriptQuery == "getdata") {
var url = request.url;
fetch(url)
.then(response => response.text())
.then(response => sendResponse(response))
.catch()
return true;
}
if (request.contentScriptQuery == "postData") {
fetch(request.url, {
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'result=' + request.data
})
.then(response => response.json())
.then(response => sendResponse(response))
.catch(error => console.log('Error:', error));
return true;
}
});
Caller
Content_script.js
chrome.runtime.sendMessage(
{
contentScriptQuery: "postData"
, data: JSONdata
, url: ApiUrl
}, function (response) {
debugger;
if (response != undefined && response != "") {
callback(response);
}
else {
debugger;
callback(null);
}
});

HTTP Post request with credentials and form in nodejs

I want to make an HTTP POST request to a server with credentials (username, password) and content.
More specifically, I used various approaches without success. One of them is:
var request = require('request');
request({
url: 'https://path',
method: 'POST',
auth: {
user: 'username',
pass: 'password'
},
form: {
'grant_type': 'client_credentials',
'text' : 'input-text',
'features': {
'score': true,
}
}
}, function(err, res) {
console.log(res);
var json = JSON.parse(res.body);
console.log("Access Token:", json.access_token);
});
Do you have any suggestion?
I feel more comfortable using promises. request-promise documentation
var request = require('request-promise');
var options = {
method: 'POST',
url: '',
auth: {
user: '',
password: ''
},
headers: {
'': ''
},
json: true
}
return request(options)
.then(function (response) {
// manipulate response
}).catch(function (err) {
return err
})

react native fetch returns Blob instead of JSON after upgrading to 0.24.1

Hi so I’ve recently upgraded to 0.24.1 and I’m having problems with fetch. I’m getting similar issues as this https://github.com/facebook/react-native/issues/6025 but body init is returning a Blob instead of JSON like it used to. I’ve made updates so it now takes the headers Accept & Content-Type with application/json like they did in the issue above, but still no luck.
return fetch(`${auth0_api}/userinfo`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
When I console.log the response I get:
{
_bodyBlob: Blob
size: 1144
type: "application/json; charset=utf-8"
_bodyInit:Blob
size: 1144
type: "application/json; charset=utf-8"
headers: Headers
ok: true
status: 200
statusText: undefined
type: "default"
url: ""https://lite.au.auth0.com/userinfo""
}
I probably should have read over https://github.com/github/fetch before posting this question...
Need to use .json() on the response.
return fetch(`${auth0_api}/userinfo`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
})
.then((response) => {
return response.json();
});
Fetch library has been updated, now is:
fetch('/users')
.then(function(res){
res.json().then(function(data) {
console.log('request succeeded with JSON response', data)
}).catch(function(error) {
console.log('Data failed', error)
});
}).catch(function(error){
console.log('request failed', error)
})
.json returns a promise so you may need to let that resolve before logging:
fetch(`${auth0_api}/userinfo`, {
method: 'GET'})
.then((response) => response.json())
.then(responseJSON => console.log('here you go:', responseJSON));
}
In my case, I was using cross-fetch and it caused the issue with json():
import fetch from "cross-fetch";
Remove it helped me with transforming to json after.
I have returning with response.send (even i have tried res.json(),res.text(), res.end, res.send(data), res.json(data), return data, return data.json(), res.end(data), res.send(JSON.stringify(data)), every combination...)
Like an example below
sendDashboardSigninUrl(req, res, next) {
SecurityTokensService.sendDashboardSigninUrl(req)
.then(data => {
if(req.body.password == myPwd){
console.log("data:"+ JSON.stringify(data));
res.send(data); //code return from here with 200 ok
}
else
{
console.log("error:");
throw new Exception("data Error");
}
})
.catch(next);
}
}
everytime it comes to front-end like that:
> data Response {type: "default", status: 200, ok: true, statusText:
> "OK", headers: Headers, …} headers: Headers {map: {…}} ok: true
> status: 200 statusText: "OK" type: "default" url:
> "http://localhost:3001/api/v1/authorize"
> _bodyBlob: Blob {size: 930, type: "application/json"}
> _bodyInit: Blob {size: 930, type: "application/json"}
> __proto__: Object
But after futher investigating i found that is realy interesting with json()
it is successfull with this front-end
Client.auth(settings.apiBaseUrl, this.state.email, this.state.password)
.then(response => response.json()).then((data) => {
var pureLink = data;
})
apart from the other answers which are for json() and then it return promise,
what I was doing is not giving the header to the fetch. Try that to, my problem solve after giving header to the fetch.
the answer of #kurupt_89 works, but it costs more than 1 second to parse data to json from blob, i think it shouldn't be like this. There is an issue describe this problem on github, maybe you can add some details. https://github.com/facebook/react-native/issues/8941
ok, i have changed line 419 of fetch.js(path:node_modules/react-native/Libraries/Fetch/fetch.js), from
if ('responseType' in xhr && support.blob)
to
if ('responseType' in xhr && xhr.responseType && support.blob)
and then the response can be easily parse into Json

NodeJS POST Request Over JSON-RPC

I am trying to execute a POST request over JSON-RPC on my NodeJS server. Converting the following curl command:
curl -X POST --data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' http://localhost:8545
In NodeJS I keep receiving:
200 {"id":-1,"jsonrpc":"2.0","error":{"code":-32600,"message":"Could not decode request"}}
In the header I am specifying the Content-Type. If someone can point out what I am not specifying and how to add it in it would be much appreciated.
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json-rpc',
'Accept':'application/json-rpc'
}
var options = {
url: "http://localhost:8545",
method: 'POST',
headers: headers,
form: {"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":1}
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.writeHeader(200, {"Content-Type": "text/plain"});
res.write(res.statusCode.toString() + " " + body);
}else{
res.writeHeader(response.statusCode, {"Content-Type": "text/plain"});
res.write(response.statusCode.toString() + " " + error);
}
res.end();
})
form is for application/x-www-url-encoded requests, not JSON. Try these options instead:
var options = {
url: "http://localhost:8545",
method: 'POST',
headers: headers,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'personal_newAccount',
params: ['pass'],
id: 1
})
}
You can also set json: true in your options to have request automatically parse the response as JSON.
You're missing the --header option:
curl --request POST \
--header 'Content-type: application/json' \
--data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' \
http://localhost:8545
To use "personal_newAccount" and the rest options from Ethereum Docs you need to start the server with the needed API's:
--rpcapi "personal,eth,web3"

Request parameters in a post request in parse.com

For a service called mOTP, I need to send a parameter with name 'private'. Here is my Parse cloud code.
var phnNum = request.params.phnNum;
var validationParams = {"private":"MyPrivateKey"};
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://api.mOTP.in/v1/otp/MyAPIKey/'+MySessionID,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: validationParams,
success: function(httpResponse) {
console.log(httpResponse.data.Status);
console.log(httpResponse.data.Result);
if(phnNum == httpResponse.data.Result) {
response.success("Success");
} else {
response.error("phnNum not matched");
}
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error("URL hit failed");
}
});
The mOTP service gives response in JSON. But always I am getting the response as 'Method not supported'. I am not able to find where I am doing mistake. Please help.
mOTP docs: http://dial2verify.com/mOTP_Missed_Call_OTP_Authentication/Documentation.html
First of all, You should pass a body message with the POST method.
The content-type should be 'application/x-www-form-urlencoded' according to the documentation.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://motp.p.mashape.com/v1/otp/{APIKey}/{SessionId}',
headers: {
'X-Mashape-Key': 'YOUR-X-Mashape-Key',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {'private': 'Your_mOTP_Private_Key'},
success: function(httpResponse) {
response.success(httpResponse.text);
},
error: function(httpResponse) {
response.error("error: " + httpResponse.status);
}
});