角度2 http发布不起作用 [英] angular 2 http post not working
问题描述
这是我的代码:
const dummydata = {
param1: 72766,
param2: 'ELS'
}
var foo = JSON.stringify(dummydata)
let headers = new Headers();
headers.append('content-type', 'application/json');
this.http.post(url, foo, { headers: headers }).map(res => res.json()).subscribe(
() => { alert('Success'); }
);
由于某些原因,在Request Payload
中没有数据作为form-data
进入服务器,并且类型已转换为OPTIONS
而不是POST
另一方面,如果我删除headers
,则form-data
将会运行,但是会发生另一个错误:
For some reason there's no data going to the server as form-data
in Request Payload
and the type is getting converted to OPTIONS
instead of POST
On the other hand if I remove, headers
, then the form-data
is going but another error occurs:
415 Unsupported Media Type
更新:jQuery Ajax正在运行
UPDATE: JQuery Ajax is working
UPDATE2:已经尝试过:
UPDATE2: Already tried this:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
推荐答案
我发现了一种更好的方法,可以通过使用Angular CLI为API调用配置代理来解决此CORS问题:
I found a better way to tackle this CORS issue by configuring a proxy for the API calls with Angular CLI:
我创建了proxy.conf.json
:
{
"/API": {
"target": "http://myserver.com",
"secure": false
},
"/API2":{
"target": "http://myserver.com",
"secure": false
}
}
然后在scripts
下的package.json
中:
"start": "ng serve --proxy-config proxy.conf.json",
现在调用API只需提供诸如"/API/getData"之类的URL,CLI就会自动重定向到http://myserver.com/API/getData
Now for calling the APIs simply provide the URLs like "/API/getData" and CLI will automatically redirect to the http://myserver.com/API/getData
这篇关于角度2 http发布不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!