所以我尝试稍微玩一下前端和后端。当尝试从前端将数据发送到服务器时,我得到了
从源“http://localhost:3000”访问“http://test.localhost/login”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“ Access-Control-Allow-Origin'标头存在于请求的资源上。
下面是我的 axios onClick 设置:
export const login = (email, password) => { return axiosClient.post('/login', { email, password }) .then(response => { // handle successful login return response.data; }) .catch(error => { // handle failed login throw error; }); };
我的 axiosClient 是:
import axios from "axios"; const axiosClient = axios.create({ baseURL: process.env.REACT_APP_API_URL, (my localhost) headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }); export default axiosClient;
我在后端的cors配置是
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class Cors { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ public function handle($request, Closure $next) { $headers = [ 'Access-Control-Allow-Origin' => 'http://localhost:3000', 'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers' => 'Content-Type, Authorization', ]; if ($request->isMethod('OPTIONS')) { return response()->json([], 200, $headers); } $response = $next($request); foreach ($headers as $key => $value) { $response->header($key, $value); } return $response; } }
您是否尝试过像这样将本地主机 IP 包含在 cors.php 中?
如果这不起作用,请尝试使用此配置
并在 Kernel.php 中注释此行,但请注意此配置将接受来自任何地方的请求,因此在部署之前确保您的后端接收来自您首选允许来源的请求。