我有自己的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请求时,服务器响应正常,Kindly click here to see the example
类别:“某些猫”
值:“ SOME VAL”
但是当我通过Angular应用发送时,
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
我在做什么错了?
答案 0 :(得分:2)
您的api需要HttpParams,因此您应该将参数设置为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
答案 1 :(得分:1)
您是否在发布请求中缺少请求参数?
{参数:{类别:'2',消息:..,...}}
因为当我使用带有请求参数的链接时,我得到200的结果。但您没有将请求参数发送到后端。
发送带有角度的请求参数或在后端请求一个请求主体。但是我对节点/表达式不熟悉。但似乎那是怎么回事。
答案 2 :(得分:0)
搜索了几个小时终于得到了解决方案 我的问题是当我将标头传递给http get或post请求时,我收到ERR_HTTP2_PROTOCOL_ERROR错误 仅当我使用有角度的http并且api在邮递员或其他带有标题的在线http投递工具上完美运行时,我才看到问题。
我提出的解决方案是转到服务器端的php文件(api文件) 并确保其仅返回不超过一个的单个回声,并检查是否需要解决任何问题。
这是我的代码
import { HttpClient , HttpParams, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Your-Api-Key'
})
};
console.log(httpOptions)
return this.http.get('http://localhost:8080/api.php',httpOptions).subscribe((data)=>{
console.log(data)
})