【问题标题】:Axios call getting blocked due to CORS error由于 CORS 错误,Axios 调用被阻止
【发布时间】:2021-10-17 04:48:51
【问题描述】:

我有一个使用 Express server 进行服务器端渲染的反应应用程序。我想使用 axios 发出 POST 请求,但它被 CORS 错误阻止: “从源 'http://localhost:4249' 访问 XMLHttpRequest 在 'https://xyz/abc' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-请求的资源上存在 Allow-Origin' 标头。

我在我的服务器调用中添加了允许源头和 cors 模块后尝试过,但没有成功

    import cors from "cors";
const server = express();
server.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Methods",
    "OPTIONS, GET, POST, PUT, PATCH, DELETE"
  );
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});
server.use(express.static("dist"));
server.use(cors());

这是 axios 请求:

const headers = {
    Accept: "application/json",
    "x-ms-version": "2019-07-11",
    Authorization: token,
    "x-ms-date": date,
    "x-ms-documentdb-isquery": true,
    "Content-Type": "application/query+json",
    "x-ms-documentdb-query-enablecrosspartition": "true",
    "cache-control": "no-cache",
    "Access-Control-Allow-Origin": "*",
  };

  useEffect(() => {
    axios
      .post(
        "https://xyz/abc",
        data,
        {
          headers: headers,
        }
      )
      .then(function (response) {
        setres(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  }, []);

Webpack 配置:

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.(sass|css|scss)$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

【问题讨论】:

  • 你为什么要与HTTP localhost 通信HTTPS:xyz?

标签: reactjs express cors


【解决方案1】:

我以前也遇到过这个问题,我就是这样做的:

app.js(后端)

server.use(cors({
  origin: '<YOUR_FRONTEND_URL_PATH>',
  methods: 'GET,HEAD,POST,PUT,DELETE',
  preflightContinue: false,
  credentials: true
}));

axios 请求:

const resp = await axios.post(
     apiUrl,
     params,
     {
        withCredentials: true,
        timeout: 10000
     }
);

【讨论】:

  • 这对我不起作用。仍然出现同样的错误
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 2023-01-19
  • 2021-12-25
  • 1970-01-01
  • 2021-10-13
  • 2019-10-01
  • 2020-09-13
  • 1970-01-01
相关资源
最近更新 更多