reactjs 从前端客户端发出请求时出现Cors错误

guykilcj  于 2023-02-08  发布在  React
关注(0)|答案(2)|浏览(354)

我有一个全栈应用程序,它停靠并部署在一个带有自定义域的VPS上,但是有一个问题,我在前端发出的请求给了我一个类似这样的Cors错误。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://backend:8080/api/link/. (Reason: CORS request did not succeed). Status code: (null).

我通常使用创建React应用程序,它不会给我这个错误,但对于这个我使用的Vite,似乎无法找出是什么原因造成的。
在后端,我添加了Springboot注解来处理Cors错误。

@CrossOrigin(origins = "*")

还在我的安全配置里禁用了Cors
在前端,我添加了指向后端(Docker服务)的代码

"proxy": "http://backend:8080",

这是我的vite.config.js

export default defineConfig({
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8080",
        changeOrigin: true,
        secure: false,
        ws: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
    port: 3000,
  },
  plugins: [react()],
});

我可以向 Postman 提出请求,它的工作原理与预期相同

4nkexdtk

4nkexdtk1#

您需要代理请求出于安全原因,浏览器将阻止CORS请求。为了避免这种情况,后端需要为您注入允许源标头。

const proxy = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(proxy('/api', {
        target: 'http://www.api.com',
        logLevel: 'debug',
        changeOrigin: true
    }));
};

或者您可以使用谷歌浏览器扩展允许CORS:访问控制允许来源链接:https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en

af7jpaap

af7jpaap2#

网上有很多建议,我也试过了大部分。
1.在控制器类上使用@CrossOrigin("URL")
1.通过HttpSecurity的对象禁用cors,如http.cors().disable();
最终,我不得不实现WebMvcConfigurer接口来解决这个问题。

@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("URL");
    }
}

希望这能帮上忙

相关问题