How to access body data before send of XMLHttpRequest - javascript

Is there a way to access and modify the body data of a XMLHttpRequest before send? I work in Angular and want to modify the request that a third-party library sends. I change the headers like this:
beforeSend(e) {
e.request.setRequestHeader(
'Authorization',
'Bearer ' + this.user.tokens.app.accessToken
);
e.request.setRequestHeader('tennant-id', this.user.tid);
}
Is there any way?

Related

TypeError on fetch request on "e-raktakosha" web site api

I am new to javascript. I was trying to make an api call.
My code
const options = {
method: 'GET',
headers: {
Authorization: 'Basic dW5kZWZpbmVkOnVuZGVmaW5lZA==',
'content-type': 'application/json',
}
};
fetch(
'https://www.eraktkosh.in/BLDAHIMS/bloodbank/nearbyBB.cnt?hmode=GETNEARBYSTOCKDETAILS&stateCode=21&districtCode=378&bloodGroup=all&bloodComponent=11&lang=0',
options
)
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => console.error(err));
but I encountered with an error saying
Error: Failed to fetch
This api call works perfectly with Hoppscotch
If I try to hit the url right on my url bar, it also works fine.
Any help is strongly appreciated. Thank you from Manoranjan
As other People already mentioned, you can't pass a Body when doing a GET HTTP call, instead you can pass Query Params
Notice this part on the URL
hmode=GETNEARBYSTOCKDETAILS&stateCode=21&districtCode=378&bloodGroup=all&bloodComponent=11&lang=0
Still looking into the code it seems the server have a cors policy, look at this sandbox
See this codesandbox -> https://codesandbox.io/s/peaceful-mcclintock-exuzol?file=/src/index.js
Summary:
GET accept body/payload but it could cause errors, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET
Using the Web API (new headers, new request) for doing the HTTP call
It is better to just avoid sending payloads in GET requests.
Please don't use body with a get request. The GET request is purely meant to collect back data from server, which allows you to sent Queries, not data on the request. Just remove body:'false' or use body:false. The best way is to remove the body from your request so unexpected input is not sent via this GET request.

Google Cloud Functions node JS - POST request from client-side fetch, request body is not coming through [duplicate]

This question already has answers here:
Can't send a post request when the 'Content-Type' is set to 'application/json'
(2 answers)
Closed 2 years ago.
I'm trying to send a POST request using Javascript fetch with application/json as the content-type and am having issues. When I do the request in Postman, it works fine. When I try to do it via Javascript fetch, I get an error and on the GCF logging side, when I try to log console.log(req.body), nothing is registered.
I am able to successfully get the request body to show up and register when I change the request content-type to text/plain and then parse the JSON after the fact in my cloud function, but I'd like to remove this extra step if possible (and also figure out why this isn't working).
Here is the client-side fetch request (essentially pasted from Postman) where the body doesn't get passed for some reason, I've tried various combinations of removing quotes from the property names and also removing the stringify:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"key1":"value1","key2":"value2"});
var requestOptions = {
method: 'post',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("mycloudfunctionsurl", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Here is my Node.JS runtime 10 Cloud Function code:
exports.helloHttp = async ( req, res ) => {
res.set('Access-Control-Allow-Origin', '*');
console.log(req.body); // <-- Shows up with Postman but not above code, unless I change to text/plain
var key1 = req.body.key1;
console.log('key1 is ' + key1);
// other functions to process the response body
};
This is probably a CORS issue. When making a cross-site request, there is an initial pre-flight request made to the function that is not request body that you posted. The fact that you see no body in the function is likely to do the fact that it's receiving this pre-flight request ahead of the intended post. Since the response isn't authorizing the cross-site request, your followup POST is never making it.
I suggest looking at this other question and use the nodejs cors module to implement it properly.

Get Authorization from HTTP-Request header

I already searched within SO for some threads about this, but could only find some which explained what this header is for or how to get the authorization header in c# but I don't want to read it from server side but from client side.
Is there any way to get the Base64 encoded header "Authorization" from the browser?
I want to implement a tool where you can log in and if you click on a spezific button your username will be saved.
My problem is that the browser does the authorization automatically, and with jQuery and JavaScript methods you can only set the requestheaders and get the responseheaders. I couldn't find a method to get the requestheaders.
The library gethttp could get some headers, but not the authorization header.
My guess is that this header is hidden.
I'm doing a login via SVN and the browser does the authorization the moment you enter the website.
Only the username is enough.
I'm searching for solutions where the user doesn't have to input their username.
I'm assuming you're trying to use the Basic Realm authorisation mechanism
This had already been replied on Stackoverflow and involves the $.ajax() jquery object.
How to use Basic Auth with jQuery and AJAX?
So please don't upvote me on this
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
where XXXXX is your username:password base64 encoded
You can use native fetch API:
fetch("http://localhost:8888/validate",{
method:"GET",
headers: {"Authorization": "Bearer xxxxx"}
})
.then(res => res.json())
.then(
(result) => {
// do something
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
// handle error
}
)
It's not possible to get the headers for the request of the CURRENT page. This has been asked several times on SO.
However, you can make a new request and retrieve the headers of that request. That way you are able to get the Basic Auth headers, base64 decode that string and then you have the username (and also the password).
Decoding base64 in javascript can be done using the following function as suggested by #michael in the comments.
window.atob("base64encodedString");

cloudinary authentication primer

I am trying to use the Cloudinary REST API, but the client libraries provided are not useful for my purpose.
So the settings I use are:
api_key = '111111111111111';
api_secret = 'fdgdsfgsdfgsdfgsdfgsdfg';
my_authorization = 'Basic ' + window.btoa(this.api_key + ':' + this.api_secret);
url_base = 'http://api.cloudinary.com/api/v1_1';
cloud_name = '/http-mysite-com';
connect_method = 'GET';
tag_list = '/tags/image';
I make the call with something similar to this:
request(tag_list) {
connection.request({
method: connect_method,
url: url_base + cloud_name + service_url,
headers: {
'Authorization': authorization,
'Content-Type': 'application/json'
}
}).then(function(response) {
// triumph
}, function(er) {
// all is lost
});
};
The response is this:
XMLHttpRequest cannot load
http://api.cloudinary.com/api/v1_1/http-mysite-com/tags/image. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://myhost:8000' is therefore not allowed
access. The response had HTTP status code 404.
What am I doing wrong?
Thanks
PS I also tried using 'https' instead of 'http', as the documentation recommends. In that case I get back:
XMLHttpRequest cannot load
https://api.cloudinary.com/v1_1/http-mysite-com/tags/image. The
request was redirected to
'http://api.cloudinary.com/api/v1_1/http-mysite-com/tags/image',
which is disallowed for cross-origin requests that require preflight.
Admin API calls use your api_secret which should not be revealed in your client-side code. That's why Cloudinary doesn't support CORS headers for the Admin API.
Therefore, Admin API calls should be performed on the server-side only.

how to change the headers for angularjs $http.jsonp

I read the document.
but I think I must have misunderstood it.
$http.defaults.headers.jsonp = { 'Accept' : 'application/json'};
$http.jsonp(url).success(function(data, status, headers, config) {
I also have tried
$httpProvider.defaults.headers.jsonp = { 'Accept' : 'application/json'};
$http.jsonp(url).success(function(data, status, headers, config) {
I wanted to change the Accept to application/json
Neither work.
There is no way to control headers sent by a browser while using JSONP. JSONP is a smart trick (or a hack, depending on how you see it...) that consist of inserting a <script> tag pointing to a server endpoint. Ultimately it is a browser who will decide which headers to sent while requesting scripts via <script> tag and you can't influence it.
More info here: Modify HTTP Headers for a JSONP request

Categories