首页 文章

CORS - 流明和角度请求

提问于
浏览
0

我有一个运行在http://localhost:4200的Angular应用程序和一个运行在http://localhost:8000的Lumen API .

我正在使用barryvdh / laravel-cors并且我的所有POSTS请求都返回“No'Access-Control-Allow-Origin'标头出现在请求的资源上 . ”

关于那个的任何线索?我的Angular数据库服务:

@Injectable()
export class DatabaseService {

  constructor(private http: Http) { }

  get(url: string) {
    return this.http.get("http://localhost:8000/" + url)
      .map(response => response.json());
  }

  post(url: string, data) {
    return this.http.post("http://localhost:8000/"+ url, data)
      .map(response => response.json());
  }

}

所有GET请求都能正常运行 .

2 回答

  • 0

    这取决于您传递的数据以及您在后端处理的方式 . 你尝试过字符串数据吗?

    JSON.stringify(data)
    
    post(url: string, data) {
    return this.http.post("http://localhost:8000/"+ url, JSON.stringify(data))
      .map(response => response.json());
    }
    
  • 0

    您需要在Lumen上授予对Angular服务器的访问权限

    如果你不使用CORS只需在/bootstrap/app.php上添加这一行

    header('Access-Control-Allow-Origin: http://localhost:4200/');
    

    或者每个人:

    header('Access-Control-Allow-Origin: *');
    

    如果您使用的是CORS,则必须在App \ Http \ Middleware \ CorsMiddleware(或任何称为您的CORS文件)的 Headers 上设置相同的内容

    $headers = [
                'Access-Control-Allow-Origin'      => '*',
                'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Max-Age'           => '86400',
                'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
            ];
    

相关问题