I am trying to load data from a rest endpoint using the HttpClient provided by Angular. The endpoint in question uses a token to authorize the user.
getData() {
if (this.token) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer' + ' ' + this.token
})
};
this.http.get('https://some url', httpOptions).subscribe((res) => {
console.log(res);
}, (error) => {
console.log(error);
});
} else {
this.empty_token = true;
}
}
I get the following error while trying to do that:
Response for preflight has invalid HTTP status code 401.
However, the same code works for a some demo url that works on "http" and not for "https".
I tried using the same by making a request using Postman or any other RestClient for that matter and it works fine.
If the calling url is http it is normal that it does not work.
This could help you https://angular.io/api/platform-browser/DomSanitizer
Or try this
private httpOptions = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + this.token});
you should add
"proxies": [
{
"path": "/v1",
"proxyUrl": "'https://some url'"
}
to your project .
you can look to this link https://github.com/mgechev/angular-seed/wiki/Add-a-Proxy-to-browsersync
Related
I have a rest-api which is returning csv file, how can i get it in the angular service.
getCSV() {
let headers_object = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': "Bearer "+ "7woNSuuEYqLfQAuqwHhCJn8aq2SM"
});
const httpOptions = {
headers: headers_object,
Accept: 'text/csv'
};
this._http.get(
'https://00.00.xx.00:9001/abcd/export', httpOptions
).subscribe(resp => {
console.log(resp)
}
);
}
Data is coming in network tab, but angular goes into the ERROR status saying http failure during parsing for because somehow it is expecting the json return.
Please help
Headers in POSTMAN as attached in image.
I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.
I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})
I'm trying to write a Post method with Axios in NodeJS.
I have following things to pass as param in post method
url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'
As I tried with following code but new to Axioz not sure how can exactly implement the header with grant type of body response.
var config = {
headers: {'Authorization': "bearer " + token}
};
var bodyParameters = {
data 'grant_type=password&username=user123&password=password123'
}
Axios.post(
'http:/xyz/oauthToken',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Any help/suggestion would be appreciated :-)
Currently, axios does not make it convenient to use form-encoded data; it's mostly optimized toward JSON. It's possible, though, as documented here.
const querystring = require('querystring');
const body = querystring.stringify({
grant_type: 'password',
username: 'user123',
password: 'password123'
});
axios.post('http:/xyz/oauthToken', body, {
headers: {
authorization: `bearer ${token}`,
'content-type': 'application/x-www-form-urlencoded'
}
});
I've seen similar threads to this issue, but I had no luck solving it.
I'm trying to access my .net core controller "GET" using angular post.
getAll() {
return this.http.get('api/Users/GetAll', this.jwt()).map((response: Response) => response.json());
}
I'm getting this error :
401 Unauthorized
jwt code :
private jwt() {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
if (currentUser && currentUser.token) {
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + currentUser.token)
return new RequestOptions({ headers: headers });
}
}
currentUser.token consist a valid token, I can access it via console.log, etc.
What am I doing wrong?