【问题标题】:What's the best CORS solution when calling 3rd party APIs?调用 3rd 方 API 时最好的 CORS 解决方案是什么?
【发布时间】:2018-08-06 09:36:20
【问题描述】:

我使用 Axios 作为我的 HTTP 客户端来调用第 3 方 API。 Express for my server 和 cors 包通过更改 HTTP 标头来解决 CORS 问题。但是错误Failed to load https://api.abalin.net/namedays?day=25&month=11: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.总是出现。

尽管使用了server.options("*", cors());,但我尝试通过使用 cors 包添加配置选项以及此website 推荐的基本配置来手动配置标头。最后,我确实将原点设置为http://http://localhost:3000/

服务器.js

const express = require("express");
const next = require("next");
const cors = require("cors");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();

    server.options("*", cors());

    server.get("*", (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, err => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

Abalin.js

class Abalin extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    Axios.get("https://api.abalin.net/namedays?day=25&month=11").then(res => {
      console.log(res);
    });
  }

  render() {
    return (
      <div>
        <p>Hello World</p>
      </div>
    );
  }
}

export default Abalin;

感谢您调查此问题。我感谢您的时间和精力。

【问题讨论】:

    标签: reactjs express cors axios next.js


    【解决方案1】:

    使用您的服务器代理 API,定义将调用 API 服务器端的路由。然后设置 cors 让你的前面调用它。

    【讨论】:

    • 我支持这个!我为我的创业公司做了这个。在向 3rd 方 api 发出请求时,我遇到了很多关于 CORS 的问题。我用我需要的路由创建了一个快速的快速服务器,把它扔到 aws 上,并给它一个用于 SSL 的子域。问题解决了!
    • 嗨@wnamen @GabrielBleu 感谢分享解决方案和经验。我花了几天时间研究这个话题,它奏效了!我确实有一些问题 1. 你们使用什么包?当我使用node-http-proxy 时,它似乎处于非活动状态。 2. 关于@wnamen 提到的子域,可以使用 express 设置还是取决于域提供者?感谢阅读!
    • 干得好,代理你不需要额外的模块,检查这个:stackoverflow.com/questions/10435407/proxy-with-express-js
    • 谢谢,@GabrielBleu!我试了一下,得到了更多的错误。我想在使用模块之前我需要对 nodejs 有更多的了解。我非常感谢您抽出宝贵时间帮助解决这个问题。 :)
    • @top22 - 抱歉,我去度假了……将子域视为一个单独的站点。例如,当我把它扔到 AWS 上时,我为 express 服务器使用了一个单独的 aws ebs 容器。容器专门映射到子域,当人们导航到子域时,他们将从该服务器而不是主站点接收代码。我希望这是有道理的!
    猜你喜欢
    • 2012-05-11
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多