Here's my code:
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'); }
);
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
UPDATE: JQuery Ajax is working
UPDATE2: Already tried this:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
答案 0 :(得分:1)
You can try this:
const dummydata = {
param1: 72766,
param2: 'ELS'
}
import {Headers, RequestOptions} from 'angular2/http';
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, dummydata, options).map(res=>res.json()).subscribe(
() => { alert('Success'); }
);
答案 1 :(得分:0)
Angular way to do post request.
const dummydata= {param1:72766,
param2:'ELS'}
var foo= JSON.stringify(dummydata);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, foo,{headers: headers} ).map(res=>res.json()).subscribe(
() => { alert('Success'); }
);
for more info check this link https://angular.io/docs/ts/latest/guide/server-communication.html
答案 2 :(得分:0)
您必须检查您的服务器是否支持OPTIONS请求,否则您需要在htaccess文件中添加这些行
标题添加Access-Control-Allow-Headers“origin,x-requested-with,content-type” 标题添加Access-Control-Allow-Methods“PUT,GET,POST,DELETE,OPTIONS”
答案 3 :(得分:0)
应该是CORS
问题。
当您从浏览器发出CORS
个请求(调用不同的URL,然后是javascript文件的主机)时,它会在发出任何其他请求之前自动发出OPTIONS
请求。如果回复合适,则会在代码中写入GET
,POST
,DELETE
,PUT
请求。
示例:强>
POST
myserver.com/add-book/
次请求
OPTIONS
myserver.com/add-book/
次请求
OPTIONS
的回复包含请求的标题等(例如,允许的方法标题)POST
请求将被执行因此,您需要在服务器和REST API上启用OPTIONS
请求。如果您使用JWT进行身份验证,则需要将OPTIONS
请求标记为安全 - JWT不需要位于请求的标头中。
有关OPTIONS
请求的More
答案 4 :(得分:0)
通过使用Angular CLI为API调用配置代理,我找到了解决此CORS问题的更好方法:
我创建了proxy.conf.json
:
{
"/API": {
"target": "http://myserver.com",
"secure": false
},
"/API2":{
"target": "http://myserver.com",
"secure": false
}
}
然后在package.json
下的scripts
:
"start": "ng serve --proxy-config proxy.conf.json",
现在调用API只需提供类似“/ API / getData”的URL,CLI将自动重定向到http://myserver.com/API/getData