前端使用VUE
接口使用 laravel
服务器用的是宝塔
1.修改laravel的cors,添加一个cors的中间件
2.需要nginx的反向代理,(nginx.conf配置文件)
- laravel 操作:https://www.cnblogs.com/phpk/p/10923128.html
中间件
在 Laravel 中允许跨域请求,我们可以在app/Http/Middleware/文件夹下构建一个追加响应的中间件Cors.php,用来添加专门处理跨域的请求的响应头:
<?php
namespace App\Http\Middleware;
use Closure;
use Response;
class Cors {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'false');
return $response;
}
}
使用中间件
在app/Http/Kernel.php文件中protected $routeMiddleware处增加'cors' => \App\Http\Middleware\Cors::class,。
需要跨域请求的路由:
Route::group(['middleware'=>'cors'], function() {
Route::any('/send','SendController@index');
});
nginx操作:https://blog.csdn.net/weixin_44692055/article/details/103693859
如果是配置了多个站点域名,需要找到nginx的子配置文件
宝塔一般在:/www/server/panel/vhost/nginx/ 路径下面
文件名一般都是域名
location /api{
proxy_pass http://xxxx.com;
add_header Content-Type "text/plain;charset=utf-8";
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST';
}