简体   繁体   English

如何使CORS HTTP请求到Angular App

[英]How to make CORS HTTP Request TO Angular App

I have an Angular 5 front end app with a PHP API on separate domains. 我有一个在单独的域上带有PHP API的Angular 5前端应用程序。 Most of the time the front end app is requesting data from the API. 大多数情况下,前端应用程序正在从API请求数据。 To enable this, I had to add a CORS Middleware class to the PHP (Laravel) project: 为此,我必须在PHP(Laravel)项目中添加CORS中间件类:

namespace App\Http\Middleware;

use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Accept')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
    }
}

In a few cases, however, I've needed to generate some HTML through PHP, and I want to request some assets (such as images and fonts) from the Angular app. 但是,在某些情况下,我需要通过PHP生成一些HTML,并且我想从Angular应用中请求一些资产(例如图像和字体)。 But when I try this, I get a CORS error. 但是,当我尝试此操作时,会收到CORS错误。 Can you tell me how I can enable CORS requests TO my Angular 5 app? 您能告诉我如何启用对Angular 5应用的CORS请求吗?

You can't make a CORS request to the client. 您无法向客户提出CORS请求。 The client makes the request. 客户端发出请求。 The server makes the response. 服务器做出响应。

If you are getting a CORS related error when a static file is requested, then you need to configure your server to put the appropriate headers in the response. 如果在请求静态文件时收到与CORS相关的错误,则需要配置服务器以在响应中放入适当的标头。

Since the response isn't handled by PHP, your middleware isn't running. 由于响应不是由PHP处理的,因此您的中间件未运行。 So you'll need to find another approach. 因此,您需要找到另一种方法。

There is plenty of documentation out there on how to configure various servers to set HTTP headers (and plenty which is specific to CORS), so identify which HTTP server you are using and look up how to do it. 关于如何配置各种服务器以设置HTTP标头的文档很多(还有很多专门针对CORS的文档),因此请确定您正在使用的HTTP服务器并查找如何执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM