前后端分离项目100%会碰到跨域问题
跨域提示
Access to XMLHttpRequest at 'http://manage.sdk.phpfunny.cn/index/portal_site/v1/home' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
什么是跨域
指的是浏览器不能执行其他网站的脚本,它是由浏览器的同源策略造成的,是浏览器对 javascript 施加的安全限制。
同源策略:
是指协议(protocol)、域名(host)、端口号(port),都必须相同,其中一个不同都会产生跨域。
http://www.test.com:8080/ 协议(http)、主域名(test)、子域名(www)、端口号(8080)
非同源策略:
无法读取非同源网页的cookie、localStorage、IndexedDB
无法接触非同源网页的DOM
无法向非同源地址发送 AJAX 请求
解决跨域方法
- JSONP
- CORS 跨域资源共享(Cross-Origin Resource Sharing)
- 反向代理
具体解释请看下方实践或者百度网上超多的教程。
[前端]nodejs+vue解决跨域
采用第三种方案 使用nodejs内置反代来绕过跨域问题
详见vue解决跨域文章,还有其他方式等待后期补充。
[后端]laravel接口解决跨域
利用框架的中间件来允许指定域名请求
- 创建中间件
cd Http/Middleware
vim EnableCrossRequestMiddleware.php
- 完善中间件内容
<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware{
/**
* @param $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
$allow_origin = [
'http://127.0.0.1:8080',//允许访问
'http://manage.sdk.xxxxx.cn',//允许访问
'http://manage.sdk.xxxxx.com/'
];
if (in_array($origin, $allow_origin)) {
$response->header('Access-Control-Allow-Origin', $origin);
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
$response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'true');
}
return $response;
}
}
- 注册中间件
在protected $middleware 里写上中间件类名。
如果没有Http/Kernel.php则需要创建
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\EnableCrossRequestMiddleware::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
];
}
完成,重新请求即可。
其他方式解决跨域
PHP项目中共享域设置
待补充
评论