I have a backend interface which I invoke with my Angular 1.3 application without problems. With my Angular 5 application I get an HTTP 403 (Forbidden)
I faced the request parameters in an picture (Angular 1.3 at the left side, Angular 5 at the right side):
My Angular 5 code looks like this:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
let options = new RequestOptions({ headers: headers });
return this.http.post(url, calendarEvent, options).map(res => res.json()).subscribe(res => console.log(res));
}
I have e.g. no idea why X-AUTH-TOKEN is not set with Angular 5 because I set it in the headers object with
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
and why OPTIONS is mentioned at Request Method with Angular 5 instead of POST like with angular 1.3.
Does anyone have any idea what I am doing wrong?
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(url, calendarEvent, Options).map(res => res.json()).subscribe(res => console.log(res));
OPTIONS request is considered as a pre-flight request, which is sent before the actual request to check the existence of method.
If the request sent is a valid one, it will call the valid method.
And regarding the request header, you can use the one in the above answer.
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
For Angular5,
import { HttpClient, HttpHeaders } from '#angular/common/http';
const headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
By default, 'Content-Type': 'application/json'
Stop using map.
Subscribe the response and store it to Observable for further access.
Example:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
return this.http.post(url, calendarEvent, {headers: headers}).subscribe(res => console.log(res));
}
Related
I am trying to connect a WebAPI build using .Net core 5
Web API: method
// POST api/<BusController>
//[EnableCors("AllowAllHeaders")]
[HttpPost]
public JsonResult Post([FromBody]BusRequest busRequest)
{
var result = "Response Text";
return new JsonResult(result);
//return result;
}
Angular 13 Code
const busRequest = {
"StartDate" : "02/15/2022",
"EndDate": "02/17/2022",
"BusNo" :null
};
**Approach 1:**
const header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded;application/json; charset=utf-8');
header.set('Accept','application/json');
const options = {headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'}),
observe: 'response' as 'response',
responseType: 'json' as 'json',
body: busRequest};
this.http.request('post', 'http://localhost:55047/api/bus', options).subscribe();
**Approach 2:**
let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'});
this.http.post('http://localhost:55047/api/bus', JSON.stringify(Request), {headers: headers}).subscribe(data => {
console.log(data);
});
But nothing works.
Response is:
tatus: 415
title: "Unsupported Media Type"
traceId: "00-403257012c151a469a0e24b083d61d62-56ac63710daf8c45-00"
type: "https://tools.ietf.org/html/rfc7231#section-6.5.13"
Did anyone faced the similar problem?
I'm trying to delete a post using a delete request, but it seems I can't get the headers right.
project-list.component.ts
deleteProject(project) {
let headers: Headers = new Headers({
'Authorization': 'Bearer ' + this.token
});
this.projectsService.deleteProject(project.id, { headers: headers }).subscribe(
result => console.log(result),
err => console.error(err)
);
}
projects.service.ts
deleteProject(id: number, { headers: headers }): Observable<Project[]>{
return this.http.delete<Project[]>(this._wpBase + 'posts/' + id);
}
The DELETE request goes to the right URL, but it's Unauthorized. Under headers it says
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://.../wp-json/wp/v2/posts/69", ok: false, …}
My guess is it's because of the "headers: HttpHeaders", but I don't know how to fix it. Any help?
You are not passing headers to the delete request. Which you have created in your component.
This is how it should go.
deleteProject(id: number, { headers: headers }): Observable<Project[]>{
return this.http.delete<Project[]>(this._wpBase + 'posts/' + id, headers);
}
Update:
Your delete won't return Project object.
deleteProject(id: number, { headers: headers }): Observable<any>{
return this.http.delete(this._wpBase + 'posts/' + id, headers);
}
Update 2:
Updated the parameter
deleteProject(id: number, headers: any): Observable<any>{
return this.http.delete(this._wpBase + 'posts/' + id, headers);
}
Try using
deleteProject(id: number, headers: any): Observable<any>{
return this.http.delete(this._wpBase + 'posts/' + id, headers);
}
I'm new to React Native and I'm calling an API with params. It looks like this.
async onSendClick() {
AsyncStorage.getItem('#Token:key').then((token) => {
console.log("console is " + token)
let subject = "Feedback Form"
let senderEmail = 'test#test.com'
let fromEmail = 'us#test.com'
let replyTo = 'customer#test.com'
let url = BASE_URL + '/email/send?'
let params = "subject=" + subject + "&email=" +senderEmail + "&fromEmail=" + fromEmail + "&replyTo=" + replyTo + "&content=" + feedBackMessage
return fetch(url + params , {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then((responseOne) => {
console.log(responseOne)
if (responseOne.status == 200) {
console.log("success")
} else{
console.log("error")
}
}).catch((error) => console.error("ERROR" + error));
})
}
In the response section , I'm getting 404 error with statusText: undefined. Please help me to fix this issue.
You must encode the URI. Otherwise it will not work.
Follow this link for more info about URL encoding in javascript.
I am new to angular 2 and currently working with angular 2.2.1 in which I am successfully able to post request and get success response however when I try to get Authorization header from response I always get null whether I am able to get Content-Type header. Below is my solution so far.
service.ts login method:
login(model: LoginModel) {
let requestUrl = '/someurl';
let requestPayload = JSON.stringify(model);
let headers = this.getHeaders(false); // ... Set all required headers
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(requestUrl, requestPayload, options) // ...using post request
//.map((res: Response)) // ...and calling .json() on the response to return data
.subscribe((res: Response) => {
var payload = res.json();
var authorization = res.headers.get('Authorization');
var contentType = res.headers.get('Content-Type');
console.log(payload, contentType, authorization)
});
}
Header Helper
getHeaders(isSecureAPI: boolean) {
let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
if (isSecureAPI) {
headers.append('Authorization', 'GetFromSession');
headers.append('X-UserID', 'GetFromSession');
}
return headers;
}
Fiddler track:
Angular Console Output
So anyone can guide me what I am possibly doing wrong?
Header was allowed but not exposed on CORS server however adding headers.add("Access-Control-Expose-Headers", "Authorization, X-Custom"); on server did the job :)
I've been trying to find a solution and came across this
Let's say I'm using the Microsoft Cors WebAPI 2 Nuget package, and I have the following global configuration in my WebApiConfig.cs:
...
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
...
The EnableCorsAttribute constructor accepts a 4th string parameter to globally allow any additional headers:
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*", "X-Foo, X-Bar, X-Baz");
I'm trying to get basic authorization to work for a Get request, but I'm getting 2 exceptions:
OPTIONS http://localhost/drupal/user/1?_format=json
XMLHttpRequest cannot load http://localhost/drupal/user/1?_format=json. Response for preflight has invalid HTTP status code 405
I'm using angular2 with drupal 8 backend
here is my service
var _baseUrl = "http://localhost/drupal";
#Injectable()
export class DrupalService {
private actionUrl: string;
constructor(private _http: Http, private _apiUrl: DrupalApi) {
this.actionUrl = _baseUrl + _apiUrl;
}
authHeaders() {
let username = 'username';
let password = 'password';
let token = btoa(username + ':' + password);
var headers = new Headers();
headers.append('Authorization', 'Basic ' + token);
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return headers;
}
public GetSingle = (id: number): Observable<Response> => {
return this._http.get(this.actionUrl + id + '?_format=json'
, {headers: this.authHeaders()}).map(res => res.json());
}
}
but it works when I try the same request from postman app
how can I fix it?
In Postman, you are sending a header:
Authorization: Basic bXVyaGFmOmhleGFkZWNpbWFsMDU
But in angular you are passing:
headers.append('Authorization', 'Basic ' + btoa('bXVyaGFmOmhleGFkZWNpbWFsMDU'));
which will end up being:
Authorization: Basic YlhWeWFHRm1PbWhsZUdGa1pXTnBiV0ZzTURV
So, just don't convert the string to base64
headers.append('Authorization', 'Basic bXVyaGFmOmhleGFkZWNpbWFsMDU');
Update
Error code 405 means : Method Not Allowed, Which means, drupal does not allow OPTIONS requests. I've not worked with Drupal before. But, there should be a way to allow OPTIONS requests.