【发布时间】:2019-10-13 09:03:34
【问题描述】:
所以,我想要做的是使用 Digital Ocean droplet 作为托管在不同服务器上的应用程序的 api。目前,我只是在开发,所以这个服务器来自我的 localhost:3000。
在我的客户端代码 (JavaScript) 上,我有:
handleSendData = () => {
const request = new XMLHttpRequest()
request.open('POST', 'http://my-droplet-ip/api/create-image')
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
request.setRequestHeader('Access-Control-Allow-Origin', 'http://my-droplet-ip')
request.send(JSON.stringify(data-object))
}
最后,在我的 Laravel 应用程序(Laravel Framework 5.8.18)中,我在routes/api.php 下有一个路由:
Route::post('/create-image', 'CreateData');
我有一个控制器CreateData.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CreateImage extends Controller
{
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function __invoke(Request $request)
{
return response('Hello World', 200)
->header('Content-Type', 'application/json; charset=UTF-8')
->header('Access-Control-Allow-Origin', '*');
}
}
问题是当我尝试运行此请求时,出现 CORS 错误:
跨域请求被阻止:同源策略不允许读取位于http://my-droplet-ip/api/create-image 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)
在网络选项卡下,我得到一个 404 not found 并且响应中没有 Access 标头。
对这个问题有什么想法吗?
【问题讨论】:
-
“在网络选项卡下我得到一个 404 not found”——所以这个问题与 CORS 没有任何关系。你弄错了网址。 (除非它谈论的是预检 OPTIONS 请求,在这种情况下,您可能完全忘记了处理该请求,但您没有引用完整的错误消息或在“网络”选项卡上提供所有详细信息)
-
我强烈推荐 github.com/barryvdh/laravel-cors 处理 CORS。
标签: javascript laravel nginx