【问题标题】:Why is fetch sending request to localhost on heroku?为什么 fetch 向 heroku 上的 localhost 发送请求?
【发布时间】:2020-09-06 01:13:53
【问题描述】:

在 server.js 我有

const PORT = process.env.PORT || 5000;

我认为这就是请求转到端口 5000 的原因,但我该如何解决呢?

我有一个快速应用程序,它服务于一个反应前端,并向同一域名上的端点发出请求。

它正在向我想要它的 some_url/auth 发送一个请求,但它也在向 localhost:5000/auth 发送一个请求,这导致我的应用程序无法工作。

甚至 package.json 也没有将代理设置为本地主机端口,所以我无法弄清楚为什么 GET 和 POST 请求会同时发送到 localhost/auth 和 some_url/auth 而不仅仅是 some_url/auth。

(客户端)app.js:

constructor(props){
    super(props);
     this.URL = 'https://reactnote-app.herokuapp.com';
    this.state = {//some stuff}
}

loginRequest = async () => {
    if (!this.state.signup) {
      console.log('login request');
      const endpoint = this.URL +'/auth'
      const res = await
      fetch(endpoint, {
        method: 'POST',
        headers : {
          'Content-type' : 'application/json'
        },
        body : JSON.stringify({
          username : document.getElementsByName('username')[0].value,
          password : document.getElementsByName('password')[0].value
        }
      )
      });
      let body = await res.text();
      console.log(body);
      this.getUsername();
    } else {
        this.createUserRequest();
    }
  }

package.json:

{
  "name": "react-notes-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "cors": "^2.8.5",
    "express-session": "^1.17.1",
    "md5": "^2.3.0",
    "mysql": "^2.18.1",
    "node-fetch": "^2.6.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.3"
  },
  "scripts": {
    "start": "node api/server.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "engines":{
    "node":"v12.18.3",
    "npm":"6.14.6"
  }
}

【问题讨论】:

  • 请告诉我们URL的定义位置和方式。
  • URLendpoint 在这个const endpoint = URL +'/auth' 中的值是多少?我建议在该声明之后添加console.log(endpoint)
  • @Bergi 它在类构造函数中定义。另请参阅我编辑的帖子。
  • 展示类构造函数。
  • @GuyIncognito 完成。检查编辑的帖子。

标签: javascript node.js heroku fetch


【解决方案1】:

我没有运行“npm run build”,所以它使用了以前的构建,它的 URL 为 localhost。 现在可以使用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    相关资源
    最近更新 更多