带有CORS和Angular的HTTP文件上传

时间:2018-12-11 11:21:32

标签: php angular cors lumen

我正在尝试生成POST / PUT请求,将文件上传到URL。 后端脚本在PHP中使用Lumen / Laravel 5.4;对于前端,我将Angular 7与 HttpClient 结合使用,以通过formdata发送文件。

现在,如果我通过POST发送任何正常数据(纯文本而不是文件),则成功,但是如果我上传文件请求,则会出现以下错误:

  • IN FIREFOX :飞行前(OPTIONS)请求后未生成POST请求,并显示一般的CORS错误:

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://storage.local/upload. (Reason: CORS request did not succeed).[Learn More]

  • IN CHROME :生成POST请求,但未显示响应,并引发net::ERR_CONNECTION_ABORTED

角度代码:

let form = new FormData();
form.append("material", mmfile);
return this.http.post(environment.storage_server, form, {
  headers: new HttpHeaders().append("authorization", token),
}).subscribe( event => {
  console.log(event)
}, error => {
  console.log(error);
}, () =>{
  console.log("done");
})

PHP脚本中的标题:

header("Access-Control-Allow-Origin", "*")
header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
header("Access-Control-Allow-Credentials", "true")
header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, Content-Length, X-Requested-With, Host, Accept-Encoding, Referer, Accept, Content-Disposition, Content-Range, Content-Disposition, Content-Description")
header("Access-Control-Max-Age", "86400");

致谢

PS:我试图解决6个小时后才写信,所以我可能错过了一些事情。随时进行编辑或索取任何详细信息。

编辑:

OPTIONS中返回的标题

    HTTP/1.0 200 OK
Date: Tue, 11 Dec 2018 12:02:20 GMT
Server: Apache/2.4.29 (Ubuntu)
Cache-Control: no-cache, private
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: AUTHORIZATION
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF

OPTIONS上发送的标头:

Host: storage.local
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization
Origin: http://localhost:4200
Connection: keep-alive

0 个答案:

没有答案