【问题标题】:Failed to fetch in production react js , rest api无法在生产中获取 react js,rest api
【发布时间】:2022-02-01 20:46:55
【问题描述】:

所以我在 heroku 上托管了我的网站。一切都很顺利并且工作正常,直到我进入使用 fetch 功能的页面。 在控制台(生产)中它说

Failed to load resource: net::ERR_CONNECTION_REFUSED
QuestionsList.js:9          Uncaught (in promise) TypeError: Failed to fetch
    at QuestionsList.js:9:19
    at s (runtime.js:63:40)
    at Generator._invoke (runtime.js:294:22)
    at Generator.next (runtime.js:119:21)
    at r (asyncToGenerator.js:3:20)
    at i (asyncToGenerator.js:25:9)
    at asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21:12
    at QuestionsList.js:8:18

我的代码问题列表组件是

const QuestionsList = () => {
  const [data, setdata] = useState([]);
  const fetchData = async () => {
    var x = await fetch("http://localhost:4000/api/v1/post");
    var parsedData = await x.json();
    setdata(parsedData.posts);
  };
  useEffect(() => {
    fetchData();
  }, []);
  return (
    <>
      <div className="container">
        <h2 className="heading-mid currentAffairs mt-3 pt-3">
          Current Affairs!!{" "}
        </h2>
        <div className="row">
          {data.map((element) => {
            return (
              <div className="col md-4" key={element.imageUrl}>
                <Question url={element.imageUrl} />
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

我认为问题出在 var x = await fetch("http://localhost:4000/api/v1/post"); 但无法弄清楚要写什么而不是localhost(我知道我必须写我的域名)。就像我会在一段时间后更改域。所以除了硬编码还有其他方法吗? 提前致谢。

【问题讨论】:

    标签: javascript reactjs fetch localhost


    【解决方案1】:

    我只是硬编码热名称而不是本地主机。 谢谢!

    【讨论】:

      【解决方案2】:

      我认为你必须将 cors orgin 添加到你的 rest api 服务器

      var express = require('express')
      var cors = require('cors')
      var app = express()
      
      var corsOptions = {
        origin: 'http://heroku .....com',
        optionsSuccessStatus: 200 
      }
      
      //...
      app.listen(80, function () {
        console.log('CORS-enabled web server listening on port 80')
      })
      

      【讨论】:

      • 我的 cors 来源是“*”,因此应该考虑每个域
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 2021-09-05
      • 2022-11-04
      • 2021-06-28
      • 2018-02-15
      相关资源
      最近更新 更多