I'm trying to POST to an API endpoint on my server. I know my endpoint works because if I use Advanced REST Client, I can hit it and get a JSON response as expected. The problem seems to be that no data is being sent in the body of my request despite calling request.write(postData) which contains a key, value pair. Without this data being sent in the body, my server returns a 401 error as expected without this information. Printing out the content of the POST server-side is empty but I'm clueless as to why it's empty.
var postData = querystring.stringify({
"access_token" : accessToken,
"id": applianceId
});
var serverError = function (e) {
log("Error", e.message);
context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server"));
};
var callback = function(response) {
var str = "";
response.on("data", function(chunk) {
str += chunk.toString("utf-8");
});
response.on("end", function() {
result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId);
context.succeed(result);
});
response.on("error", serverError);
};
var options = {
hostname: REMOTE_CLOUD_HOSTNAME,
port: 443,
path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var request = https.request(options, callback);
request.on("error", serverError);
//This doesn't seem to write anything since if I print out the POST
//data server-side it's empty; however, if I print out the value of
//postData here, it looks as expected: 'access_token=xxxxx'
request.write(postData);
request.end();
I have testing you code again httpbin.org/post and it seems that it is working.
I believe that the issue related to, that your should POST application/json and not "application/x-www-form-urlencoded
Please try to change the header
headers: {
"Content-Type": "application/json"
}
Then, try to change the postData to JSON string:
var postData=JSON.stringify({access_token:"xxxxx"})
To be sure that problem you success to send and the problem is not local (maybe there is an issue in your server), change the target to mirror URL:
var options = {
hostname: "httpbin.org",
path:'/post',
port: 443,
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
If there is no problem in your NodeJS version, the is the response you should get: (It is mean that the server got the posted data)
{
"args": {},
"data": "{\"access_token\":\"xxxxx\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": {
"access_token": "xxxxx"
},
"origin": "5.29.63.30",
"url": "https://httpbin.org/post"
}
BTW: I really recommend you to move to a library to manage the request for you:
https://github.com/request/request - Very popular
https://github.com/request/request-promise - For popular who like to use the Promise syntax (The next thing in JavaScript)
https://github.com/visionmedia/superagent - For people who like to write same code in Browser & Server
Related
Hi everyone recently i have been trying to do a fetch post in app script, from an api called salesbinder(inventory system), i have managed to fetch and pulls all inventory data down, however i have been struggling to post and add document to it and received an error code ->
"Truncated server response: {"message":"Unauthorized","url":"\/api\/2.0\/documents.json","code":401}"
since I am using the same username and password I can assure that the details are correct for the authentication, would appreciate a lot if anyone could help me to solve the problem.
Here are the api documentaion (https://www.salesbinder.com/api/documents/add/) and the code i have been using.
function posting(){
var Username = "{API KEY}"
var Password = "x"
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(Username+ ':' + Password)
};
var url ='{API URL}'
var data ={
"document":{
"customer_id": 'a93a9e9a-5837-4ec5-9dc7-47cc8cfd84e4',
"issue_date":"2022-05-09",
"context_id":5,
"document_items":[
{
"quantity":2,
"price":134,
"item_id":" b04993fe-7b17-42a1-b5e5-2d34890794c9"
}
]
},
};
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
UrlFetchApp.fetch(url, option);
}
I think that your error message of "message":"Unauthorized" is due to "headers": {headers},. This has already been mentioned in chrisg86's comment.
And also, from this document, it seems that the request body is required to be sent with Content-Type: application/json.
From:
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
To:
var option = {
"method": "post",
"payload": JSON.stringify(data),
headers, // or "headers": headers
"contentType": "application/json"
};
Note:
In this modification, it supposes that the values of "Basic " + Utilities.base64Encode(Username+ ':' + Password), data and url are correct. Please be careful this.
I have attempted to create a request in javascript, that has previously worked using python just fine.
the following is an accurate representation of the code I used to post the request with python:
url = 'https://website.com/api/e1'
header = {
'authorization': 'abcd1234'
}
payload = {
'content': "text",
}
r = requests.post(url, data=payload,headers=header )
This (above) works just fine in python.
now what I did in javascript is the following:
payload = {
"content": "this is text",
};
fetch("https://website.com/api/e1", {
method: "POST",
headers: {
"authorization":
"abcd1234",
},
body: JSON.stringify(payload),
});
but this is returning the error
400- Bad request
When using data parameters on python requests.post, the default Content-Type is application/x-www-form-urlencoded(I couldn't find it on the document, but I checked the request. If you know, please leave a comment).
To achieve the same result with fetch, you must do as follows.
const payload = {
'content': 'this is text',
};
fetch('https://website.com/api/e1', {
method: 'POST',
headers: {
'authorization': 'abcd1234',
},
body: new URLSearchParams(payload),
});
You don't need to do this body: JSON.stringify(payload), rather you can simply pass payload in body like this body:payload
I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});
I'm building a REST api on top of express.js. I am having trouble updating variables inside my routes.
Example:
I'm calling app.get("/wp/page/create/:id", function(req, res)
Inside this route I start by calling a http request using request-promise library. The response of this call I use in a nested http call.
I use a global variable for the headers for the nested call, and it's to the header a i need to make changes by using the etag variable.
Code:
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
res.send(data).end()
console.log("All done!");
})
})
When i start the server up and enter the route everything works fine. When i when try to hit it again the etag variables is still the same, even though it should be updated.
If I restart the server it works the again on the first attempt but fails on the second/third.
Any idea what I am doing wrong?
I have resolved the issues. The simple solution was to clear the headers containing the variable.
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
postHeaders['If-Match'] = "";
res.send(data).end()
console.log("All done!");
})
})
postHeaders is a global variable. is headers in global.postHeaders = headers; also a global varaible ? Whatever you are trying to do here is grossly wrong. postHeaders variable will be shared across multiple request. so you will hit a scenario where postHeaders['If-Match'] value might be empty string or the etag .
Try this instead of the first line
var postHeaders = Object.assign({}, headers);
Not sure what you are trying, but at-least this statement will subside the huge error in the code. This will create a new header object for each request.
This seems very similar to a number of other questions and it seems obvious that the error indicates there's something wrong with my JSON payload. But I'm at a loss as to why.
I'm running a Google Apps Script to test sending a message to Google Firebase Cloud Messaging.
My code:
function SendGCMessage() {
var url = "https://gcm-http.googleapis.com/gcm/send";
var apiKey = "AbCdEfG";
var to = "ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"
var payload = {
"data": {
"message" : "This is the message"
},
"to":to
};
var sendCount = 1;
var headers = {
"Content-Type": "application/json",
"Authorization": "key=" + apiKey
};
var params = {
headers: headers,
method: "post",
payload: payload
};
var response = UrlFetchApp.fetch(url, params);
return {message: "send completed: " + response.getContentText()};
}
When I run this in debug mode, the object payload looks fine - like a normal Javascript object. params as well. UrlFetchApp takes a Javascript object, not a String in JSON notation. However I did try "JSON.stringify(params)" and I got an error. What did I do wrong?
Note: params looks like this when I pause it in the debugger:
{"headers":{"Content-Type":"application/json","Authorization":"key=AbCdEfG"},"method":"post","payload":{"data":{"message":"This
is the message"},"to":"ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"}}
I discovered the problem, thanks to https://stackoverflow.com/a/10894233/3576831
the 'payload' parameter must be a string as specified here:
https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
Adjusting this section of the script works:
var params = {
headers: headers,
method: "post",
payload: JSON.stringify(payload)
};