I'm trying to send content-type headers for the below post request to allow json request, but it throws me an error Invalid CORS request with OPTIONS request method. It doesn't even send POST method.
Here, I cannot able to use RequestOptions which is depreciated.
PS: This is working fine when I send the request with postman. And, Backend code is handled with CORS request already.
From Backend java code, this the error I'm getting
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
Where am I missing?
postSubmit(){
let data = { "name":"John", "age":30 };
const httpHeaders = new HttpHeaders ({
'Content-Type': 'application/json'
});
return this.http.post<any>(apiURL, data, {headers : httpHeaders})
.pipe(catchError(error => this.handleError(error)))
}
}
To define the content-type with the new HttpHeaders class you need to
Just Import import { HttpHeaders } from '#angular/common/http';
Create httpOptions object that will be passed to every HttpClient save method
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
Call the API this.http.post<Datatype>(API url, Bady Parameter, httpOptions)
Related
I have a method that fires a fetch function. It also sets headers over which type I would like to have control.
// Request headers
let headers: HttpHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
// Checks if user have x-auth-token cookie
const token = getCookie(AUTH.COOKIE_NAME);
if (token !== null) {
headers = {
...headers,
[AUTH.API_TOKEN]: token
};
}
// Request body
const request = {
method,
headers,
body: JSON.stringify(body)
};
if (body || method.toUpperCase() === HttpMethod.GET) {
delete request.body;
}
I have also enum, which holds all allowed headers:
export enum HttpHeader {
ACCEPT = 'Accept',
CONTENT_TYPE = 'Content-Type',
X_AUTH_TOKEN = 'x-auth-token'
}
I already know that you can't specify enum as the expected index value in the ts interface. Can you give me another option to control http request headers? I saw the idea of using an array of objects, but I have the impression that it is a bit of a form over content.
You can use an enum to define a type that has all the enum values as keys using a mapped type (what you can't do is have an enum as an index parameter).
The predefined Record and Partial mapped types will do the job nicely:
type HttpHeaders = Partial<Record<HttpHeader, string>>
export enum HttpHeader {
ACCEPT = 'Accept',
CONTENT_TYPE = 'Content-Type',
X_AUTH_TOKEN = 'x-auth-token'
}
// Request headers
let headers: HttpHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
headers = {
...headers,
[HttpHeader.X_AUTH_TOKEN]: "token"
};
Play
I am trying to send a custom HTTP Header from the front end app for it to interact with the gateway. This is my angular function:
import {Http, Headers, Response, RequestOptions } from ‘#angular/http’;
getXById(id :number){
let options = nee RequestOptions({ headers : new Headers({“X-fastgate-resource” :”resource_name}) });
return this.http.get( http://url + “/resource”, options)
I expected to see a Header with, “X-fastgate-resource” as a key, and “resource_name” as value.
What I got was this:
Request Headers:
OPTIONS http://url HTTP/1.1
host...
Access-Control-Request-Headers: x-fastgate-resource
You could try out something like below.
let headers = new HttpHeaders();
headers.append('X-fastgate-resource', 'Example');
let options = { headers: headers };
let apiUrl: string = 'http://url';
this.http.get(apiUrl, options);
Hope this helps
Try This code:
import {HttpHeaders} from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
**With params**
const url = 'yourapi';
return this.http.post(url, {
key: value,
key1: value1
},httpOptions);
**Without Params**
const url = 'yourapi';
return this.http.post(url,httpOptions);
Try using the Angular Context.
Angular Context
This is the simplest way I know of passing data, usually to an interceptor
Define a Context Token - usually in the interceptor
export const MY_FILENAME = new HttpContextToken<string>(() => "");
Pass the data
const context = new HttpContext().set(MY_FILENAME, `${name}.pdf`)
return this.httpClient.post(url, pdf, {context: context})
Collect the data. Usually in the interceptor
const fileName = request.context.get(MY_FILENAME)
I am hitting an api for getting userinfo, for that I am passing header authorization with value, but in options method it is firing and giving error that https status code 401, authentication required.
I am trying the same with Chrome browser and Postman client tool then it's giving me desired result. Why only my app is throwing such error? It's supposed to give me result if I am giving authorization header for that.
For instance, code is like:
this.http.get(this.url,{headers:this.headers});
Try setting withCredentials : true .
Here is my Working Code. Hope it helps. Also note Iam using new httpclient of Angular 5.
emailsignin(username: string, password: string) { .
let url = this.backendUrl + "/index";
let params = 'username='+username+'&password='+password;
let httpheaders = new HttpHeaders(
{
'Content-Type': 'application/x-www-form-urlencoded'
});
return this._httpclient.post(url, params, {headers: httpheaders, withCredentials : true});
}
You should define your options as a RequestOptions object:
let options = new RequestOptions({ headers: new Headers({ 'Authorization': 'Basic xxxx' }) });
this.http.get(this.url,options );
I m trying to call a web service from Angular. I m passing the headers as HttpHeaders object, but I do not see that sent when I check the Network console.
This other post Angular HttpClient doesn't send header
seems to have answered it, but I am not able to get that working with the solution that is suggested in it .
My call looks like this.
1
this.http.get(urlString, {headers: new HttpHeaders({'Content-Type': 'application/json',
'header1': 'value1',
'header2': 'value2'
})});
2
let myHeaders = new HttpHeaders();
myHeaders = myHeaders.set( 'Content-Type', 'application/json')
.set( 'header1', 'value1')
.set( 'header2', 'value2')
;
this.http.get(urlString, {headers: myHeaders});
3
const httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/json',
'header1': 'value1',
'header2': 'value2'
})
};
this.http.get(urlString, httpOptions);
In all cases, the Network console shows this
Access-Control-Request-Headers:content-type,header1,header2
Is there some mistake which I am making when I declare or set it? Sorry if this question is repetition of others, but the answers were not working in this code. Thank you.
Use Headers instead of HttpHeaders
const headers = new Headers({'Content-Type' : 'application/json','header1':'value1','header2':'value2'})
return this.http.get('url', {headers: headers});
I am working on a sample Angular2 application which uses Spotify API to get data. When I run the code, I'm getting response Error in console as "Invalid Access Token". I have provided the correct access token, still the error persists, I'm not getting how to resolve it and what's wrong I'm doing.
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class SpotifyService {
private searchUrl: string;
constructor(private _http: Http) { }
searchMusic(str: string, type = 'artist') {
const access_token = '<My Access Token Here>';
const headers = new Headers({ 'Authorization': 'Bearer ' + access_token });
this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type+'&market=US';
return this._http
.get(this.searchUrl, { headers })
.map(res => res.json());
}
}
Error Screenshot :
You can check by adding one of the content-type in headers
var headers: Headers = new Headers({'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/x-www-form-urlencoded' });
OR
var headers: Headers = new Headers({'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json' });
were you able to get a valid response by giving your access token in their api console?
https://developer.spotify.com/web-api/console/get-search-item/?q=tania+bowra&type=artist