I am pretty new in Babel and trying to make a POST request with header "Content-Type" as "application/json". Is there any documentation for changing the headers of Request ?
import Request from 'request-promise-native'
const result = await Request
.post(`some url`)
.auth(authId, secretToken,false)
.form({
text: "hello"
})
console.log(result);
return JSON.parse(result)
Just add a headers object like so:
.headers({
'Content-Type': 'application/json'
})
Related
I want to add an authorization to header, I've already assign to header before like in the code below
const axiosIns = axios.create({
baseURL: 'http:$$$$$$$$$$/api/app',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
Then I added interceptor and assigned token to authorization header
axiosIns.interceptors.request.use(async config => {
const accessToken = await authService.getAccessToken()
config.headers.Authorization = `Bearer ${accessToken}`
return config
})
but typescript put red line below config.headers says Object is possibly 'undefined'
The error message "Object is possibly 'undefined'" is indicating that the TypeScript compiler is not sure if the "config.headers" object is defined or not. This can happen if the "config" object passed to the request interceptor does not have a "headers" property. To fix this, you can add a check for the "headers" property before trying to access it.
You can add a check to ensure the headers object is defined before trying to add the Authorization header.
axiosIns.interceptors.request.use(async config => {
const accessToken = await authService.getAccessToken()
if (config.headers) {
config.headers.Authorization = `Bearer ${accessToken}`
}
return config
});
This way, if the headers property is undefined, you will skip the assignment and not get the error.
axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
config.headers['Authorization'] = auth;
return config
})
you can red more there
I have an axios request to the backend. And our backend said that he already configure the cors for the front end. But when I send my axios request. It only gets me this headers even if I put an header in my post request.
Here is my axios
for (var i = 0; i < this.rows.length; i++) {
console.log(this.rows[i].from)
console.log(this.rows[i].to)
axios.post(' https://pa-staging.propnex.net/index.php/public/addDiyOpenhouse?listing-id=506&start-time='+this.rows[i].from +'&end-time='+this.rows[i].to+'&date=2020-06-20',{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((res)=>{
console.log(res);
})
}
The axios.post API dictates that the second parameter is for data (like form data or json, etc) and headers can be defined in the third parameter. So change you line to this syntax:
axios.post(url, requestData (or empty object for no data), {headers: { headerName: headerValue }})
I have built an API and app that uses that API. When I POST method via Postman, it works fine, but when I try fetching it via app, I get a bad request 400 status response. What am I doing wrong?
Here is my JavaScript code:
const myForm = document.getElementById('loginForm');
myForm.addEventListener('submit', function(e) {
e.preventDefault();
const url = 'https://thawing-peak-69345.herokuapp.com/api/auth';
const myHeaders = new Headers();
myHeaders.append('Accept', 'application/json, text/html, */* ');
myHeaders.append('Content-Type', 'application/json, charset=utf-8')
const formData = {
email: this.email.value,
password: this.password.value
};
console.log(formData);
const fetchOptions = {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: myHeaders,
body: JSON.stringify(formData)
};
fetch(url, fetchOptions)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
})
Request
Response
Headers request:
Headers response:
You said:
mode: 'no-cors',
This is a declaration that you are not doing anything that requires permission be granted with CORS. If you try to do anything that does need permission, it will be silently ignored.
myHeaders.append( 'Content-Type', 'application/json, charset=utf-8')
Setting the Content-Type header to a value not supported by the HTML form element's type attribute requires permission from CORS. application/json is not such a value.
Consequently, the request is sent as text/plain.
Since it isn't marked as being JSON, the server throws a 400 error.
You need to:
Remove mode: 'no-cors',
Make sure that the service you are making the request to will use CORS to grant you permission (or to use a service on the same origin as the request).
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' });
I am trying to make an HTTP POST request with Angular 2 as below.
saveUserSelection() {
var json = JSON.stringify({access_token: localStorage.getItem('access_token')});
var params = 'json=' + json;
var headers = new Headers();
headers.append({ 'Content-Type': 'application/json' });
return this.http
.post('http://localhost:8080/user/selection', params, { headers: headers })
.map(res => res.json());
}
But I am getting an error as below.
angular2.dev.js:23877 EXCEPTION: Error during evaluation of "ngSubmit"
ORIGINAL EXCEPTION: SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': '[object Object]' is not a valid HTTP header field name.
Does anyone have an idea what's wrong with my code? And how can I create a HTTP POST request with parsing body type parameter?
This should do what you want:
headers.append('Content-Type', 'application/json' );
headers.append('access_token', localStorage.getItem('access_token'));