Hey i have implemented an api which is a GET request
now what i want is Response Header values but only some of them are showing in the api reponse but in network tab every value is showing
i dont know what is the problem
this is my Http service
pendingResultData(payload: Payload, headerConfig?: {}) {
const params = payload
? {
type: payload.type,
data_scopes: payload.data_scopes,
observe: 'response',
...headerConfig
}
: { observe: 'response', ...headerConfig };
const reqUrl = '/api/data_capture';
return this.timerService.timer(this.httpService.getFullResponse(reqUrl, params));
}
this is my interceptor
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.idToken = this.authService.getAccessToken() || '';
// cloning original request and set/add new headers
const authReq = req.clone({
headers: this.idToken
? req.headers
.set('Authorization', `Bearer ${this.idToken}`)
.set('Access-Control-Allow-Origin', '*')
.set('Content-Type', 'application/json')
.set("Access-Control-Expose-Headers", "*")
: req.headers,
params: req.params
});
return next.handle(authReq);
}
now the headers are coming in response header you can see in Screen shot
i want total, current-page, per-page but headers i am getting in api response are
headers: "content-length: 194
content-type: application/json; charset=utf-8
cache-control: max-age=0, private, must-revalidate"
i wanna know am i doing something wrong and if this a backend problem or not?
any help?
thanks
You can access these by user response.headers.get() method. e.g:
this.httpService.getFullResponse(reqUrl, params).subscribe(response=> {
console.log(response.headers.get('per-page'));
});
i think you have to add your custom headers to "access-control-expose-headers" in the backend response. In your screenshot from above it looks that their are not in the list.
(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers)
https://github.com/angular/angular/issues/5237#issuecomment-441081290
Related
I'm trying to send an http request using fetch to my backend but it's returning this error even though I'm sending an application/json header,
the content that needs to reach the api is a json
front-end code
let user_ = 'teste';
let email_ = 'teste#email.com';
let pass_ = 'teste';
let button_submit = document.getElementById('mySubmit_signup');
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Credentials', 'true');
button_submit.addEventListener('click', async function(){
try {
await fetch('http://localhost:8080/users', {
mode: 'cors',
method: 'POST',
body: JSON.stringify({
name: user_,
email: email_,
password: pass_
}),
})
.then(
response => response.json()
)
.then(
data => console.log(data)
)
} catch (error) {
console.log(error);
}
});
ATT:
i add header but i receive "Access to fetch at 'http://localhost:8080/users' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
try {
await fetch('http://localhost:8080/users', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
name: "user_",
email: "mail_#email.com",
password: "pass_"
}),
})
.then(
response => response.json()
)
.then(
data => console.log(data)
)
} catch (error) {
console.log(error);
}
};
req();
You are passing a string to body. This means fetch will automatically add a Content-Type request header saying that you are sending plain text.
Your server side code is expecting JSON and is rejecting your so-called plain text with an error.
You need to explicitly add the correct header to say that you are sending JSON.
headers: {
'Content-Type': 'application/json',
},
Aside Do not add 'Access-Control-Allow-Origin': '*', to your request headers. This is a response header and has no business being on the request. Adding it will create additional problems.
Adding an application/json content type to the request will make it preflighted.
You quoted an error mentioning a preflight request. The error state may have been caused by your incorrect extra header (see the aside above) or it might be that your server isn’t set up to support any preflight request.
If the latter then you need to adjust the server-side code to response to the preflight request (which is OPTIONS rather than POST) to give permission to the browser to make the POST request you want to make.
I have a problem with CORS. I can do a GET request but it's impossible to do a POST or PUT Request.
I use AWS API GateWay to do my API. My APi works with postman.
I have these errors: error 500
My code :
postUsersHTTP(request:any): Promise<Response> {
let headers = new Headers({
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT",
"Access-Control-Allow-Headers": "X-Custom-Header"
});
let options = new RequestOptions({ headers: headers });
return this._http.post(environment.baseURL + "/user", request, options).toPromise()
.then(this.extractData)
.catch(this.handleErrorPromise);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
private handleErrorPromise (error: Response | any) {
console.error(error.message || error);
return Promise.reject(error.message || error);
}
I see a lot of answer on stackoverflow but not reallly usefull for my error Thanks !
I've been there, I've done that!
that's call X-Scripting protection.
Install this extension to your Chrome, and you'll be good to go.
Allow-Control-Allow-Origin: *
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
I've got a function that logs in a user, and the response gives me the token in the body, which i set in headers.
this.headers = new HttpHeaders({'Content-Type': 'application/json'});
loginUser(email, password) {
const body = {email, password};
return this.http.post(`${this.serverUrl}/users/login`, body, {
observe: 'response',
headers: this.headers
})
.pipe(
tap(res => {
if (res.body['token']) {
this.jwtToken = res.body['token'];
this.headers.set('x-auth', this.jwtToken);
this.router.navigate(['/firms/create']);
}
})
);
}
Then, when I try to use those headers to send a request for logging out, I see that the 'x-auth' header is not present. But I clearly set it in the loginUser function.
Here's my logout function:
logoutUser() {
return this.http.delete(`${this.serverUrl}/users/me/token`, {
observe: 'response',
headers: this.headers
})
.pipe(
tap(res => {
this.headers.delete('x-auth');
this.removeTokenFromLocalStorage(this.jwtToken);
this.jwtToken = null;
})
);
}
And these are the headers that I'm sending to the server on my LOGOUT call (notice how I don't have the x-auth there, although I should!)
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:
Connection:keep-alive
Content-Type:application/json
Host: censored
Origin:http://evil.com/
Referer:http://localhost:4200/somendpoint
User-Agent:
Side-note: My back-end is set up to intercept req.headers['x-auth'] and do login with that (in the auth middleware).
Any help would be appreciated.
HttpHeaders is immutable - it doesn't change, it must be reassigned.
Change the line to:
this.headers = this.headers.set('x-auth', this.jwtToken);
And in your delete function:
this.headers = this.headers.delete('x-auth');
And it should work.
I'm trying to send data with http post following differents threads, but I can't do it.
I need to send this data, tested in postman.
Headers.
Content-Type: application/x-www-form-urlencoded
Authorization: Basic user:pass
Body.
grant_type: password
scope: profile
This is my code.
login() {
let url = URL_LOGIN;
let headers = new Headers(
{
'Content-Type': 'application/json',
'Authorization': 'Basic user:pass'
});
let body = {
'grant_type': 'password',
'scope': 'profile'
}
return this.http.post(url, body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
}
Thanks in advance!!
There are two things you need to modify:
Your headers passed into the http post method missed one step. It should contain the following:
let options = new RequestOptions({ headers: headers });
Ensure you import RequestOptions from #angular/http
Then pass options into your post method as follows:
return this.http.post(url, body, options)...
The http post method body can only be a string. Therefore, it should be as follows:
let body = 'grant_type=password' + '&scope=profile';
I have an webapp react.js / redux / webpackt / es6... and an api in go with mux from gorilla.
When I make call with the function below my header is empty and content too.
I'm using this package in my webapp to make calls
"isomorphic-fetch": "^2.2.1",
My call example
export function Login(userData) {
return dispatch => {
fetch(API + '/login', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userData.email,
password: userData.password,
}),
})
.then(response => {
console.log(response);
console.log(response.statusText);
console.log(response.status);
console.log(response.headers);
console.log(response.headers.get("Authorization"));
console.log(response.json());
return response.json()
if (response.status >= 200 && response.status < 300) {
console.log(response);
dispatch(LoginSuccess(response));
} else {
const error = new Error(response.statusText);
error.response = response;
dispatch(LoginError(error));
throw error;
}
}).then(function(json) {
console.log('parsed json' + json)
})
.catch(error => { console.log('request failed', error); });
}
In the beginning I had a problem with cors How to handle preflight CORS requests on a Go server I used this solution
We can look the call inside of the console :
login OPTIONS 200 fetch auths.actions.js:38 352 B 1 ms
login POST 200 json Other 567 B 82 ms
When I look inside of my POST Header response I have :
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin: http://localhost:3000
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NTQ3NTcxNjEsInVzZXJfaWQiOiI1NmI1YjZlOTFhZTMzYjAwMDFhYmE1MTQifQ.WGoTMxm6OuN24Olwr93J3pND9dFLCtG5MyiRbqLWeD244JtDzq0bGgQMixeZxyuxwGK3u8KhyWD7Rr6iZAGNpA
Content-Type: application/json
Date: Sat, 06 Feb 2016 11:12:41 GMT
Content-Length: 2
So the response handle my preflight information not my POST ? Because there is nothing inside of the response.headers and response.headers.get("Authorization")
There is something wrong ?
I had the problem that my headers were sent, correctly received (chrome's network tab correctly shows me all the sent headers), but I couldn't access them in js (response.headers was empty). As described in Fetch get request returns empty headers, this happened because the server did not set the Access-Control-Expose-Headers header, resulting in the needed headers not to be exposed to js.
So the solution is to add this header on the server and voilà, now the headers are accessible in js:
Access-Control-Expose-Headers: <header-name>, <header-name>, ...
The header takes a comma-separated list of header-names to be exposed to the browser.
For additional info on why this header is needed, see Why is Access-Control-Expose-Headers needed?