POST方法在Angular2中不起作用
Posted
技术标签:
【中文标题】POST方法在Angular2中不起作用【英文标题】:POST method not working in Angular2 【发布时间】:2017-01-28 03:37:17 【问题描述】:我是 Angular2 的新手。我正在尝试从 Angular2 调用简单的 java REST 调用。当我发布数据时,我根本没有收到错误,但我的 java post 方法没有被调用。
Angular2 POST-
let emplyee = JSON.stringify(this.object);
let url = 'http://localhost:8080/rest-app/rest/employeeService/insertEmployee';
console.log("Data: " + emplyee);
let headers = new Headers('Content-Type': 'application/json');
let options = new RequestOptions(headers: headers);
this.http.post(url, emplyee, options);
Java POST 方法-
@POST
@Path("/insertEmployee")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String insertEmployee(String employee)
logger.debug("Employee: " + employee);
return "Hello";
【问题讨论】:
您得到的回应是什么?在this.http.post()
之后添加.subscribe(res => console.log(res))
到console.log
响应。
@Supamiu thnx 用于响应,我得到了这个响应,对预检请求的响应未通过访问控制检查:请求中不存在“Access-Control-Allow-Origin”标头资源。因此不允许访问 Origin 'localhost:3000'。
【参考方案1】:
这里的问题是预检结果没有通过。
您必须在您的 Java API 中允许 CORS 请求(您必须添加 Access-Control-Allow-Origin *
标头,请参阅您的 API 库文档以了解如何添加它)。
这就是您在订阅中收到错误的原因,因为您的预检请求未通过。
编辑:有关该问题的更多解释,请参阅 How to make CORS-enabled HTTP requests in Angular 2?。
【讨论】:
【参考方案2】:你需要像这样添加订阅-
this.http.post(url, emplyee, options)
.subscribe((response) =>
//handle response here
)
.catch(this.handleError);
如果你想使用 Promise,那么就这样使用它-
this.http.post(url, employee, options)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
【讨论】:
以上是关于POST方法在Angular2中不起作用的主要内容,如果未能解决你的问题,请参考以下文章