Angular http request with body and headers - javascript

I am trying to access https://grocerybear.com/#docs sample api request which is shown in the documentation as
curl -H "api-key: 123ABC" \
-H "Content-Type: application/json" \
-X POST \
-d '{"city":"LA", "product":"bread", "num_days": 10}' \
https://grocerybear.com/getitems
I used a website online to convert this into a javascript fetch function and got this:
fetch("https://grocerybear.com/getitems", {
body: "{\"city\":\"LA\", \"product\":\"bread\", \"num_days\": 10}",
headers: {
"Api-Key": "123ABC",
"Content-Type": "application/json"
},
method: "POST"
})
I tested this with javascript with my developer key and it worked, however I want to use the http methods in Angular 9 to get the data.
I tried this:
getData(){
const options = {
headers: new HttpHeaders(
{
"Api-Key": '(myDeveloper key was inserted here in the program)' as const,
"Content-Type": 'application/json' as const
}
),
body: "{\"city\":\"LA\", \"product\":\"bread\", \"num_days\": 10}"
};
return this.http.get(`https://grocerybear.com/getitems`, options);
}
and it returned a 400 error when I tried to log it to the page.
When I changed it to a post method request instead of a get method then it also returns a 400 error.
Does anybody know how to implement this to get the proper data back?
Thanks!

I just figured it out!
the correct code would've been:
getData(){
const body = {city:"LA", product:"bread", num_days: 10}
const options = {
headers: new HttpHeaders(
{
"Api-Key": 'API KEY inserted here' as const,
"Content-Type": 'application/json' as const
}
)
};
return this.http.post('https://grocerybear.com/getitems', body, options);
}
}

Related

Request in javascript (from python)

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

Getting variable from array then pass to url on nodejs request module

I have this array and need to pass all the variables inside the request url.
I've tried as result.variable1, result['variable1'], result[0], but nothing works.
How can access each variable inside the array and pass to url?
result.push({variable1: string1, variable2: string2});
request.post({
url: "mydomain.com/text="Hi"+result[variable1]+"\\n"+result[variable2]+"Hello!",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
rejectUnauthorized: false,//add when working with https sites
requestCert: false,//add when working with https sites
agent: false,//add when working with https sites
form: {
myfield: "myfieldvalue"
}
}, function (response, err, body){
console.log('Body:',JSON.parse(body));
}.bind(this));
result.push({variable1: string1, variable2: string2});
This will result in the array becoming as
result = [{variable1: string1, variable2: string2}].
So if you want 'variable1', you need to access it as result[0].variable1.

Cache Storage API, can't get header back

I would like to a check for max-age so I remove items from cache when they get old, but I can't get my own header back for some reason.
export function cacheResponse(url, response) {
caches.open('my-cache').then(function(cache) {
cache.put(url, new Response(JSON.stringify(response), {
headers: {
'Cache-Control': 'max-age=1',
'Content-Type': 'application/json;charset=UTF-8'
}
}));
});
}
cacheResponse('/hello', {hello: "world"})
I can see this working in the Application tab in chrome and I can see those 2 headers in the preview, but when I pull the item back out the headers object is null.
cache.match(url).then(async function(object) {
console.log(object.headers) // null
var body = await object.clone().json(); // {hello: "world"}
})
The object looks like this
object: Response
body: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: ""
type: "default"
url: ""
Seems like I should be able to lookup the headers from calling match() no?
That should work; you should be able to call response.headers.get('cache-control') to retrieve the value (assuming this is a same-origin response).
Here's a snippet of code that I just tested which worked when run in the JS console:
async function test() {
const constructedResponse = new Response('test', {
headers: {'cache-control': 'max-age=1'}
});
const cache = await caches.open('test');
cache.put('/test', constructedResponse);
const matchedResponse = await cache.match('/test');
console.log(`cache-control: ${matchedResponse.headers.get('cache-control')}`);
}

Alternative headers to "application/x-www-form-urlencoded"

So I have a funny little problem.
When calling my API from an AngularJS client with the following code, everything works fine, except that my API only recieves an empty object as data:
var req = {
method: 'Post',
url: config.API + request.toLowerCase() + '/',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: data
}
$http(req)
.then(function(response){
// handling response
})
Now, if I remove the headers: { 'Content-Type': 'application/x-www-form-urlencoded' } or changes it to headers: { 'Content-Type': 'application/json' } I get the this error:
The requested resource does not support http method 'OPTIONS'
My API controller looks like this:
[EnableCors("*", "*", "*")]
[HttpPost]
public string Post([FromBody]dynamic value)
{
// Do some stuff
Response response = new Response();
return JsonConvert.SerializeObject(response);
}
What I'm looking for is a way to prevent the tiresome "OPTIONS not supported" error, and still be able to send dynamic data to my controller
EDIT
Regarding the duplicate, I've already tried their approach, hence why I already are using [EnableCors] in my controller. But if I add this:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
}
I get this error instead
Response to preflight request doesn't pass access control check: The
'Access-Control-Allow-Origin' header contains multiple values '*, *',
but only one is allowed. Origin 'http://localhost:82' is therefore not
allowed access

HTTPS request not posting body of REST request

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

Categories