Javascript Fetch API: header params not working - javascript

This is my sample request:
var header = new Headers({
'Platform-Version': 1,
'App-Version': 1,
'Platform': 'FrontEnd'
});
var myInit = {
method : 'GET',
headers: header,
mode : 'no-cors',
cache : 'default'
}
fetch('http://localhost:3000/api/front_end/v1/login', myInit)
.then(res => {
console.log(res.text())
})
When I debug, I see that this request is sent successfully to server, but server hasn't received header params (in this case is Platform-Version, App-Version and Platform). Please tell me which part do I config wrong.
thanks

You are using it correctly, but you have to tell your backend service to allow custom headers (X-). For example, in PHP:
header("Access-Control-Allow-Headers: X-Requested-With");
Also, your custom headers should be prefixed with X-. So you should have:
'X-Platform-Version': '1'
And one last thing, your mode needs to be cors.
You can see that standard headers are being sent with the following code. take a look at the network tab to see the standard request headers.
var header = new Headers();
// Your server does not currently allow this one
header.append('X-Platform-Version', 1);
// You will see this one in the log in the network tab
header.append("Content-Type", "text/plain");
var myInit = {
method: 'GET',
headers: header,
mode: 'cors',
cache: 'default'
}
fetch('http://localhost:3000/api/front_end/v1/login', myInit)
.then(res => {
console.log(res.text())
});

Related

No response from API

I have created an API call in excel to get data from a Wix database.
The call:
Dim http As Object, JSON As Object
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://username.wixsite.com/mysite/_functions/Functionname", False
http.setRequestHeader "Authorization", "myauthkey"
http.Send
MsgBox (http.responseText)
The javascript http backend file on Wix:
import { ok, notFound, serverError } from 'wix-http-functions';
import wixData from 'wixdata';
export function get_Wixdata() {
let options = {
"headers": {
"content-type": "application/json"
}
};
return wixData.query("wix data collection name")
.find()
.then(results => {
if (results.items.length > 0) {
options.body ={
"items": results.items
}
return ok(options);
}
})
}
I tested the call (without authorisation) on JSON place holder and it worked fine.
Just trying to debug what's happening as I am getting "" as a response.
Even if I enter the wrong API key I still get "", even a wrong url it's still a "" response.
I take it I am clearly way off the mark with what I am trying to do..
Did you tried put both headers in your request, like the following:
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': '....'
});
The issue was with the VBA call, the header was not needed.
Dim https As Object, JSON As Object
Set https = CreateObject("MSXML2.XMLHTTP")
With CreateObject("Microsoft.XMLHTTP")
.Open "GET", "end point url", False
.send
response = .responseText
End With

How to customize HTTP_USER_AGENT header with Graphene and React Native?

I found that React Native does not give HTTP_USER_AGENT value to Django Graphene. On Garaphene, I receive the header by:
def resolve(cls, root, info, **kwargs):
info.context.META['HTTP_USER_AGENT']
It works when I send a query through a browser. However, the HTTP_USER_AGENT only has "okhttp/3.6.0" value when I send a query through my React Native app. So I tried to change the HTTP_USER_AGENT value by setting headers of axios.
onSubmit = async () => {
if (!this.state.isSubmitting) {
this.setState({isSubmitting: true});
await axios({
url: 'http://192.168.0.6:8000/graphql/',
method: 'post',
headers: {
HTTP_USER_AGENT: 'CCC'
},
data: {
query: `
It does not work. HTTP_USER_AGENT does not change and only shows "okhttp/3.6.0". I tried other custom headers and found that they do not work either. I cannot just set my own custom-named-header. Why is this the case? The only header I was available to change was AUTHORIZATION. Django Graphene received the header value when I set
await axios({
url: 'http://192.168.0.6:8000/graphql/',
method: 'post',
headers: {
AUTHORIZATION: 'JWT CCC'
},
and the value was available from
info.context.META['HTTP_AUTHORIZATION']
I had no idea if my assumptions were wrong.
Solved it luckily.
You have to set 'USER-AGENT' header on your client side(React Native)
await axios({
url: 'http://192.168.0.6:8000/graphql/',
method: 'post',
timeout: 5000,
headers: {
'USER-AGENT': await Constants.getWebViewUserAgentAsync(),
},
And receive the value as HTTP_USER_AGENT on your server side (Django Graphene)
ua_string = info.context.META['HTTP_USER_AGENT']
user_agent = parse(ua_string)
I do not know why their names are different (it took me half a day) but this is how it is.

Node JS - Constructing an OAuth2 Request

Im trying to construct an OAuth2 request to the Box API. The example POST request they give as a guideline is a bit ambiguous to me as I am recently learning backend development. The example is as follows:
POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&
assertion=<JWT>&
client_id=<client_id>&
client_secret=<client_secret>
Official Docs:
https://box-content.readme.io/docs/app-auth
The way I attempted to do this is as follows:
var boxHeaders = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var boxOptions = {
url: 'https://api.box.com/oauth2/token',
method: 'POST',
headers: boxHeaders,
form: {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': boxtoken,
'client_id': 'myclientid',
'client_secret': 'myclientsecret'
}
};
request.post(boxOptions, function(err, response, body) {
console.log(body);
});
I get the following error:
{
"error":"invalid_request",
"error_description":"Invalid grant_type parameter or parameter missing"
}
Obviously the grant type is incorrect but I have no idea how to go about constructing the string based on the Box API example. If anyone can help and even expose me to some good articles or tutorials on how to do this, that would be great!
Thank you.
I just struggled with this myself. I was able to get this to work by moving everything you currently have in boxOptions.form into the request body.
For example:
var boxHeaders = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var boxOptions = {
url: 'https://api.box.com/oauth2/token',
method: 'POST',
headers: boxHeaders
};
var form = {
grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',
client_id: 'id',
client_secret: 'secret',
assertion: boxtoken
};
var request = https.request(boxOptions, function(response) {
// do stuff
});
request.write(querystring.stringify(form));
request.end();
Hope this helps. Unfortunately, I'm not familiar enough with the request library to provide an example using it.

Parsing AngularJS http.post data on server side with express & body-parser

I just recently started learning MEAN stack so forgive me if this seems like a really dumb question. My problem is as follows:
On the client side (controller.js) I have,
$http({
method : 'POST',
url : '/root',
// set the headers so angular passing info as form data (not request payload)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
data : {
type:'root',
username:$scope.rEmail,
password:$scope.rPassword
}
})
On the server side I have,
app.post('/root', function(req, res) {
console.log(req.body);
console.log(req.body.username);
});
My console log shows:
17 Nov 21:39:04 - [nodemon] starting `node server/server.js`
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
undefined
I would imagine req.body.username to give me testUserName but I get undefined. The JSON format I am getting is slightly weird. Can anyone help me out this one? I did some reading and tried using body-parser and went through angular js $http.post documentation but didn't find anything that would help me out.
I imagine the problem is at:
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
but I cant seem to figure out how I would pass the data from $http.post in my angular controller so that I would just get my request in identifier:value format.
Nevermind, I figured it out. Seems like I needed a break from coding.
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
to
headers : { 'Content-Type': 'application/json' }
fixed the problem.
Try my source code below:
$http({
method : 'POST',
url : '/root',
// set the headers so angular passing info as form data (not request payload)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
data : {
type:'root',
username:$scope.rEmail,
password:$scope.rPassword
},
transformRequest: function(obj) {
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
return str.join('&');
}
})
$http({
method : 'POST',
url : '/root',
// set the headers so angular passing info as form data (not request payload)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
params : {
type:'root',
username:$scope.rEmail,
password:$scope.rPassword
}
})
try it with 'params', maybe it won't work but try it :P
I've tried with "params" instead of "data" and worked ok, and doesn't matter if headers are "application/x-www-form-urlencoded" or "application/json"
But using "application/json" works with request.query.param1 on node.

Sending 'Authorization' header in Ext JS Ajax Request, Chrome vs. Firefox

In code the request is sent as:
var ajaxOptions = {
url: 'someUrl',
method: 'POST',
success: function(response) {
...
},
failure: function(response) {
console.log(response);
}
};
var form = this.getView().getForm();
var submitAction = Ext.create('Ext.form.action.Submit', { form: form });
var formInfo = submitAction.buildForm();
ajaxOptions.form = formInfo.formEl;
if (form.hasUpload()) {
ajaxOptions.isUpload = true;
}
Ext.Ajax.request(ajaxOptions);
When a request is sent via Chrome, the 'Authorization' header presents:
Authorization:Basic YWRtaW46YWRtaW4=
When it is sent via Firefox, the header is not included.
Explicitely I don't set user/password. So it's not clear, why and how chrome sends such header. Are there any known issues?
The second, how to force firefox to send such header? Is it possible?
UPDATED
JavaScript does not now anything about login/password. The main question, how Chrome can use them, but other browsers cannot send such pair. So the question is how to force other browsers to send this cookie as Chrome does without appling headers manually via JavaScript.
On the server side, the Servlet API is used. in web.xml:
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>someName</realm-name>
</login-config>
if it does matter
Per the docs, just add a headers property to your ajaxOptions:
ajaxOptions = {
//...
headers : {
'Authorization': 'Basic YWRtaW46YWRtaW4='
}
}

Categories

Resources