Http状态不正常:修改标题

时间:2018-10-29 19:06:36

标签: angular http-headers

在AngularJS中的几个项目之后,第一次开发了一个angular 6项目,我遇到了一个CORS问题(至少我是这样认为的。)

我一直想要做的是从mysql服务器检索我的数据。我知道,Angular无法直接与Mysql交谈。 因此,我使用以下php API:https://github.com/mevdschee/php-crud-api

我在http.get()上取得了成功,但在http.post()上却没有。 控制台将引发错误:404错误和消息:预检响应没有HTTP正常状态。

在Stackoverflow上阅读所有答案,我认为这与修改标头有关。因此,如您在我的代码中所见,我在请求中添加了标题。但是没有结果。 我的项目在localhost:4200上运行,而我用来检索数据的api在localhost:80上

非常感谢您的帮助!

这是我的代码:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

@Injectable()
export class ServerService {

constructor(private http: Http) { }

public api = 'http://127.0.0.1/';

storeServers(servers: any[]) {
 const headers: Headers = new Headers({
   'Access-Control-Allow-Origin':  'http://127.0.0.1/',
   'Access-Control-Allow-Methods': 'POST',
   'Access-Control-Allow-Headers': 'Content-Type'
 });
 return this.http.post(this.api+'/Angular_6/http- start/api.php/testservers', servers, {headers: headers});
}

 getServers(){
  return this.http.get(this.api+'/Angular_6/http-start/api.php/testservers?transform=1');
 }
}

我通过添加代理文件解决了该问题。看到这个:https://www.youtube.com/watch?v=OjmZPPKaj6A

1 个答案:

答案 0 :(得分:0)

您需要启用和配置PHP-CRUD-API的cors中间件(在PHP配置中设置允许的来源)以允许跨域请求。然后,您可以在浏览器的开发人员工具的“网络”标签中看到“ OPTIONS”请求。您应该确认它的响应状态为200 OK(并且没有被您的网络服务器阻止)。

NB:我是PHP-CRUD-API的作者