我有自己的API和POST
路由,其工作方式如下:
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);
});
当我从其他来源发送HTTP POST请求时,服务器响应良好,请单击此处查看示例
类别:“ SOME CAT”
值:“ SOME VAL”
但是当我通过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.');
}
});
}
}
我收到以下错误。
{"category":"message","value":"asdasd"}
Server-side error occured.
OPTIONS https://sizilkrishna.000webhostapp.com/api/public/api/log net::ERR_HTTP2_PROTOCOL_ERROR
我究竟做错了什么?
你的api需要HttpParams,因此你应该将params设置为params而不是body:
const params = new HttpParams().set("category", category).set("value", value);
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
}),
params: params
};
然后将身体设为null
:
return this.http
.post<any>(
this.apiUrl + "/log",
null,
httpOptions
)
// .....
这似乎很好用:STACKBLITZ
谢谢,它的工作。但是我如何将httpOptions和queryParams结合在一起?
用的示例更新了我的答案
Accept
,因为您无法添加标头,'Content-Type':'application/json'
因为这不是您发送的:)是的,但是最初我是在使用
PUT
请求,所以我回滚到POST
进行调试。现在,有了您的解决方案,我可以回到实现我的原始代码!再次感谢。:)