Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
/** ... */
public sendData(s: string, k: any) {
let h = new Headers();
h.append('Content-Type', 'application/json');
h.append('Accept', 'application/json');
let content = JSON.stringify({
username: s,
key: k
});
console.log(content);
return this.httpService.post(SERVER_URL, content, {
headers: h
})
.map((res: Response) => {
return res.json();
});
}
On the server side, here's the Express code in TypeScript:
public handleWhitelistRequest(req: Request, res: Response) {
let out: boolean;
console.log("post request received"); //DEBUG
if (req.body.key) {
out = wl.submit(req.body.username, req.body.key);
} else {
out = wl.submit(req.body.username, {});
}
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.json({
username: req.body.username,
success: out
});
}
If you're getting a 'CORS' error message when calling the Angular 2 code to send requests, check the header settings. Also, make sure that the 'post request received' message is logged to the console for debugging purposes.
Some additional details and debug findings:
- Sending POST requests via Postman to the server works as expected.
- GET requests are functioning correctly, even when sent from Angular.
It seems like there might be an issue with how the Angular code sends the content. Any insights on this would be greatly appreciated. Thank you!