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.
Related
I have inherited a codebase using Axios, and I am otherwise unfamiliar with the library. This is a Node application, and I'm attempting to send a PATCH request to a third party API. Axios is configured using the following:
const axios = require('axios').create({
baseURL: process.env.API_URL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
auth: {
username: process.env.API_USER,
password: process.env.API_PW,
},
});
I then try to make the following PATCH request:
const data = {
fields: {
field_a: 'yes',
field_b: 'no',
},
};
try {
const res = await axios.patch(`/user/${user.id}`, data, {
headers: {
'Content-Type': 'application/json'
}
});
return res;
} catch (err){
console.error(err);
}
From what I can see I'm just redefining the Content-Type header when making the patch call, but that was just an attempt to figure this out. It doesn't work either way. What I see in the response object's config property is the following (most of it is excluded):
{
headers: {
Accept: "application/json"
User-Agent: "axios/0.19.0"
},
method: 'patch',
}
Looking at the request property of the same response object I see that the method there is listed as "GET" with the Content-Type header also not listed there. It appears as though the Content-Type header is being stripped and the method is being changed to GET.
If I change nothing but the URL destination to /userWRONGPATH/${user.id} I receive, as expected, a 404 response, but the response object's config data includes this:
{
headers: {
Accept: "application/json"
Content-Length: 105
Content-Type: "application/json"
User-Agent: "axios/0.19.0"
}
}
The response object's request method is now the expected 'PATCH'. I am unsure why the patch method would work for other paths if that is in fact what is happening here.
Hello I think that the problem could be related of send the header again in Axios you define a config and that is added to all the requests.
This is an example that I use to order the project with axios.
// Axios custom config
const axiosInstance = axios.create({
baseURL: urlBase,
// timeout: 1000,
headers: { 'Content-type': 'application/json' },
});
export const apiPatchRequest = (url, id, obj) => (
axiosInstance.patch(`${url}/${id}`, obj)
);
While executing the below code I am getting the token such format like Bearer {token}
Now While gitting the getOrderList() I am getting a 400 Bad Request error.
I am not sure what am I doing wrong? I am using this https://documentation.b2c.commercecloud.salesforce.com/DOC1/index.jsp?topic=%2Fcom.demandware.dochelp%2FOCAPI%2F15.2%2Fshop%2FResources%2FOrders.html as a reference to fetch all orders from the salesforce while is created recently.
Can anyone help me with this thing?
'use strict';
const fetch = require('node-fetch');
const ocapi_path = require('./ocapi_path');
const envDomain = 'Domainhere';
const envClientId = 'clientidHere';
const getToken = async (domain = envDomain, clientId = envClientId) => {
const response = await fetch(
`${domain}/s/site-id/dw/shop/v19_1/customers/auth?client_id=${clientId}`,
{
method: 'POST',
body: JSON.stringify({ type: 'guest' }),
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
},
},
);
if (!response.ok) {
const json = await response.json();
throw new Error(`OCAPI error response: ${JSON.stringify(json)}`);
}
return response.headers.get('Authorization');
};
const getOrderList = async (token) => {
const domain = envDomain;
const response = await fetch(
`${domain}/s/site-id/dw/shop/v19_1/orders?status=completed`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Cookie': token,
Authorization: token,
},
},
);
if (response.ok) {
return await response.json();
}
return null;
};
const getTheResult = async () => {
const token = await getToken();
const result = await getOrderList(token);
console.log(result);
}
getTheResult();
You need to exchange the access token for session credentials and then use those to call the Orders API.
Retrieve token for guest (you've done this)
Exchange token for session creds:
To obtain a session for a guest or registered customer
you have to pass a valid JWT to /sessions resource. The JWT has to be
passed as Authorization:Bearer request header. In case of success you
get the session cookies back.
REQUEST:
POST /dw/shop/v20_2/sessions HTTP/1.1
Host: example.com
x-dw-client-id: ...
Authorization: Bearer <token>
RESPONSE:
HTTP/1.1 204 NO CONTENT
Set-Cookie : dwsecuretoken_a85a5236a2e852d714eb6f1585efb61c=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT;
Set-Cookie : dwsid=eXv5R3FZGI4BBfbK1Opk5s1mJ-41Aw7ZuaMKxeye5xa16fJMX--AnNkXsvmakbi1UZSzP1zoPmUILgoom1_jKg==;
Set-Cookie : dwanonymous_a85a5236a2e852d714eb6f1585efb61c=bdjalnzmfrkJ0FtYliwud5db67; Max-Age=15552000;
Cache-Control: max-age=0,no-cache,no-store,must-revalidate
Call Order API with session creds from previous step:
REQUEST:
GET /dw/shop/v15_2/orders?status=completed HTTP/1.1
Host: example.com
Cookie: dwsecuretoken_a85a5236a2e852d714eb6f1585efb61c="";dwsid=eXv5R3FZGI4BBfbK1Opk5s1mJ-41Aw7ZuaMKxeye5xa16fJMX--AnNkXsvmakbi1UZSzP1zoPmUILgoom1_jKg==; dwanonymous_a85a5236a2e852d714eb6f1585efb61c=bdjalnzmfrkJ0FtYliwud5db67;
Content-Type: application/json; charset=UTF-8
RESPONSE:
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
{
"_v" : "15.2",
"count" : ...,
"data" : [...],
...
}
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
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?