i'm facing the issue that when i set header i'm unable to send the token to the API.one more strange issue is that when i see in my network log, i can see method getting converted to 'OPTION', also my 'Token' is not being sent. see below Error :
i have tried to find out all the ways but nothing worked for me, can anyone help here.
Reffered questions :
Using http rest apis with angular 2
Angular2 OPTIONS method sent when asking for http.GET
My code :
//set token for Authorization
setHeaders() {
var token = this.localStorageService.getToken();
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
headers.append('Authorization', token);
this.options = new RequestOptions({ headers: headers });
}
//function
getMaintenanceType() {
this.setHeaders();
return this.http.get(this.url_Configuration.maintenancetype, this.options)
.map(res => res.json())
}
Please try to use below solution, it will work.
Set Header with the request :
Create a method setHeader :
setHeader(): RequestOptions {
let headers = new Headers()
headers.append('Accept', 'application/json');
headers.append("X-Auth-Token", this.accesToken);
let options = new RequestOptions({ headers: headers });
return options;
}
And then Use it :
this.http.get(this.baseURL + url, this.setHeader()).map(res => res.json());
I see that you are having Error Code 403. By Any chance, is your server running on a different platform like 'apache, JBOSS, ... etc' and your UI application is on different. If that is the case, You need to implement CORS support to your server, and I can help you with it, once you confirm the server environment.
As of now, I see a couple of things that can be changed in your code, for starters, and this might help too:
headers ;
headers = new Headers ({ 'Content-Type': 'application/json' });
this.headers.append('Accept', 'application/json');
this.headers.append("X-Auth-Token", this.accesToken);
let options = new RequestOptions({ headers: headers, method: 'get' });
Related
I am trying to access a JSON endpoint using Javascript with X-Auth-Token but I’m keeping getting error. It’s JSON for a sports API and I’ve followed every instruction in the documentation and code seems to correct to my knowledge however, I can’t spot the problem.
var main = function() {
var url = "https://api.football-data.org/v4/teams/86/matches?status=SCHEDULED";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.setRequestHeader("X-Auth-Token", "601a163917fe417da759316ced98462d");
xhr.send(null);
var data = JSON.parse(xhr.responseText);
return data;};
You need to set the request mode to no-cors for it to allow cross-origin resource sharing.
Try doing this.
var myHeaders = new Headers();
myHeaders.append("X-Auth-Token", "your token");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow',
mode: 'no-cors'
};
fetch("https://api.football-data.org/v4/matches?status=FINISHED", requestOptions)
.then(result => console.log(result))
.catch(error => console.log('error', error));
Hope it helps.
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'm trying to send a post request from my Ionic 3 (Angular 5) app to my REST api, but I'm getting HTTP 404 (Not found) or HTTP 400 (Bad request).
When I send the post request using Postman it is successful. And also, my GET request in Ionic 3 app works successfully. You can see success request below, it hasn't an Authorization:
Here is my request method:
sendConfirmationCode() {
let mybody = new FormData();
mybody.append('msisdn', '1234567');
let myheaders = new HttpHeaders({
'Content-Type': 'application/json'
});
this.http.post('http://mydomain/methodname', mybody, {headers: myheaders})
.subscribe(data => {
console.log(JSON.stringify(data));
}, error => {
console.log(JSON.stringify(error));
})
}
With headers I get HTTP 404 (Not found) but without HTTP 400 (Bad request). So, I tried different body objects with and without using headers. Here is my usings instead of FormData body object:
let mybody= new HttpParams();
mybody.append('msisdn', '1234567');
-----
let mybody= new URLSearchParams()
mybody.append('msisdn', '1234567');
-----
//SubscriberDataInput is my class for to use as input body model of api's method
let mybody = new SubscriberDataInput();
mybody.msisdn = '1234567';
-----
let mybody = JSON.stringify({ "msisdn": "1234567" });
And tried these cases for sending header instead of above header:
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
-----
let headers = { 'Content-Type': 'application/json' }
None of them works successfully. Can you please tell the right way?
I found the solution. The problem was my RESTful api prevents ajax post requests. This is a solution in Asp.Net WebApi 2 which related Cors:
Add a constant into Startup class of Startup.cs :
private const string DefaultCorsPolicyName = "localhost";
Add Cors into ConfigureServices method of Startup class:
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Enable Cors in Configure method of Startup class:
app.UseCors(DefaultCorsPolicyName); //Enable CORS!
Delete first custom header in web.config:
<add name="Access-Control-Allow-Origin" value="*"/>
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?
I m using Isomorphic fetch in my application and I m having some troubles dealing with CSRF.
Actually, I m having a backend that sends me a CSRF-TOKEN in set-cookies property :
I have read somewhere that it's not possible, or it's a bad practice to access this kind of cookies directly inside of my code.
This way, I tried to make something using the credentials property of fetch request :
const headers = new Headers({
'Content-Type': 'x-www-form-urlencoded'
});
return this.fetcher(url, {
method: 'POST',
headers,
credentials: 'include',
body: JSON.stringify({
email: 'mail#mail.fr',
password: 'password'
})
});
This way, I m able to send my CSRF cookie back to my server to serve my need (it's a different one, because it s not the same request) :
My problem
My problem is that my backend needs to receive a x-csrf-token header and so I can't set it to my POST request.
What I need
How can I do to put the value of set-cookies: CSRF-TOKEN into the next request x-csrf-token header ?
It looks like in your scenario you are supposed to read from CSRF-TOKEN cookie. Otherwise it would be marked HttpOnly as JSESSIONID. The later means you cannot access it from the web page but merely send back to server automatically.
In general there is nothing wrong in reading CSRF token from cookies. Please check this good discussion: Why is it common to put CSRF prevention tokens in cookies?
You can read your cookie (not HttpOnly, of cause) using the following code
function getCookie(name) {
if (!document.cookie) {
return null;
}
const xsrfCookies = document.cookie.split(';')
.map(c => c.trim())
.filter(c => c.startsWith(name + '='));
if (xsrfCookies.length === 0) {
return null;
}
return decodeURIComponent(xsrfCookies[0].split('=')[1]);
}
So fetch call could look like
const csrfToken = getCookie('CSRF-TOKEN');
const headers = new Headers({
'Content-Type': 'x-www-form-urlencoded',
'X-CSRF-TOKEN': csrfToken
});
return this.fetcher(url, {
method: 'POST',
headers,
credentials: 'include',
body: JSON.stringify({
email: 'test#example.com',
password: 'password'
})
});
Yes header name depends on your server. For example django usecase to setup CSRF token using fetch is like this:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
'X-CSRFToken': get_token
},