I have my own API and a POST
route working as follows,
Server
// Handling CORS with a simple lazy CORS
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization, application/json')
->withHeader('Access-Control-Allow-Methods', 'GET, POST')
->withHeader('Content-Type','application/json')
->withHeader('X-Powered-By','Mercurial API');
});
...
$app->post('/api/log', function( Request $request, Response $response){
$category = $request->getParam('category');
$value = $request->getParam('value');
return logQuery($category, $value, $response);
});
When i am sending a HTTP POST Request from other sources the server is responding fine, Kindly click here to see the example
category:"SOME CAT"
value:"SOME VAL"
But when i sending the same through my Angular App,
const httpOptions = {
headers: new HttpHeaders({
'Content-Type':'application/json'
})
};
...
public putLog(category: string, value: string) {
// You can add new argument in header like,
// httpOptions.headers = httpOptions.headers.set('Authorization', 'my-new-auth-token');
const body = JSON.stringify({ category: category, value: value });
console.log(body);
return this.http.post<any>(this.apiUrl + '/log', body, httpOptions)
.subscribe(
data => {
console.log('PUT Request is successful.');
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('Client-side error occured.');
} else {
console.log('Server-side error occured.');
}
});
}
}
i am getting the following error.
{"category":"message","value":"asdasd"}
Server-side error occured.
OPTIONS https://sizilkrishna.000webhostapp.com/api/public/api/log net::ERR_HTTP2_PROTOCOL_ERROR
What am i doing wrong?
Your api expects HttpParams, so you should set your params as params and not body:
const params = new HttpParams().set("category", category).set("value", value);
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
}),
params: params
};
and then have body as null
:
return this.http
.post<any>(
this.apiUrl + "/log",
null,
httpOptions
)
// .....
That seems to work just fine: STACKBLITZ
Thanks, It worked. But how would i combine httpOptions along with the queryParams?
Updated my answer with sample with
Accept
, since you cannot add header'Content-Type':'application/json'
as that is not what you send :)True, but originally i was using
PUT
request, i rolled back toPOST
for debugging. Now with your solution i can go back to implementing my original code! Thanks again. :)