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);
}
Related
I executed a WebService using Postman and it's executed correctly. And now i want to send a request to the WebService using Angular
Here is the Asp.net Web Service
This is the code for my WebService
public class Temperature : System.Web.Services.WebService
{
[WebMethod]
public double Farenheit(double celsius)
{
return (celsius * 9) / 5 + 32;
}
[WebMethod]
public double Celsius(double fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
}
And this is the screenshot on how i send a request using PostMan and it's working as expected
Screenshot for Calling the WebService using Postman
Here is the code for the Angular
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text/xml',
})
};
this.http.post('https://localhost:44389/Temperature.asmx/Celsius', '50', httpOptions)
.subscribe(res => {
console.log('Data: ' + res);
})
And this is the error I'm receiving
Error
"System.InvalidOperationException: Request format is invalid: text/xml.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
"
Message
Http failure response for https://localhost:44389/Temperature.asmx/Celsius: 500 OK
Name
"HttpErrorResponse"
Change your 'Content-Type': 'text/xml' to 'Content-Type': 'application/json'
try this :
import { HttpHeaders } from '#angular/common/http';
setHttpHeader() {
const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
let options = { headers: headers };
return options;
}
this.http.post('https://localhost:44389/Temperature.asmx/Celsius', '50', this.setHttpHeader())
.subscribe(res => {
console.log('Data: ' + res);
})
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));
}
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.
My Ionic 2 app have few providers and they communicate with a secured API over http, so I have to include an authorization header contains bearer token (which I stored in localstorage) with every request I made.
My current (ugly) implementation is for each function, am appending header like below sample code,
getAccountDetails(accountId: string): Promise<any> {
let url = API_ENDPOINT + 'some-string';
return new Promise(resolve => {
this.userData.hasLoggedIn().then((hasLoggedIn) => {
if (hasLoggedIn) {
this.userData.getUserToken().then((token) => {
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
this.http.post(url, { id: accountId }, { headers: headers }).map(res => res.json()).subscribe(data => {
resolve(data);
});
})
}
})
});
}
As I mentioned above, for each functions now I repeat the same header append code, how can I make it DRY (avoid repeating the same code)?
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.