【问题标题】:404 (Not Found) when attempting to POST information to heroku尝试将信息发布到 heroku 时出现 404(未找到)
【发布时间】:2020-08-23 10:24:52
【问题描述】:

我有一个具有快速后端的 React 应用程序。我正在尝试从我的前端获取到我的后端。这个获取是一个登录,我通过各种凭据检查我的 clearDB 以查看用户是否合法。出于某种原因,我收到了 404 未找到。好消息是 404 表示我的后端和前端通信良好,但坏消息是它无法正常访问路由。我在这里提供了一些文件。如果您需要任何其他文件,请告诉我。一如既往,我感谢您的支持并期待这次讨论。

文件夹结构:

DemoApp
  >bin
  >classes
  >client
    ->build
    ->node_modules
    ->public
    ->public
    ->src
    ->package.json
    ->static.json
  >Design
  >node_modules
  >public
  >routes
    ->api.js
  >views
  app.js
  package.json

控制台日志:

Login.js:69 POST https://<hostname>.herokuapp.com/api/login 404 (Not Found)

app.js(NodeJS 后端):

...
const corsOptions = {
   origin: 'http://localhost:3000',
   credentials: true
}
app.use(cors(corsOptions))

app.use('/', express.static(path.join(__dirname, '/client/build')));

app.get('*', function(request, response) {
    response.sendFile(path.join(__dirname, '/client/build', 'index.html'));
});

package.json(位于客户端文件夹中):

{
  "name": "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",
    "bootstrap": "^4.4.1",
    "email-validator": "^2.0.4",
    "owasp-password-strength-test": "^1.3.0",
    "password-validator": "^5.0.3",
    "prop-types": "^15.7.2",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-dropdown": "^1.7.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1",
    "semantic-ui-react": "^0.88.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "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"
    ]
  }
}

static.json

{
  "root": "build/",
   "routes": {
    "/assets/*": "/assets/",
    "/**": "index.html"
  }
}

Login.js(反应组件):

const url = '/api/login'

fetch(url, {
 method: 'POST',
 credentials: 'include',
 headers: {
     'Content-Type': 'application/json'
 },
 body: JSON.stringify(user)
 })

api.js(NodeJS 后端路由)

   .
   .
   .

    var connection = mysql.createPool('mysql://<username>:<password>@<host>/<database name>?reconnect=true')
    router.post('/login', function(req,response,next) {
        const query1 = "SELECT * FROM users WHERE username = TRIM(?)"
        connection.query(query1, [req.body.username], function(err, result) {
            if (err) {
                response.json({'message': 'Incorrect Username/Password', 'status': 0})
            } else {
                req.session.username = req.body.username
                response.json({'message': 'You have successfully logged in', 'status': 1})
            }
        })
    })

【问题讨论】:

    标签: javascript node.js reactjs heroku deployment


    【解决方案1】:

    如果您在不同于 app.js 的另一个文件中声明路由器,您应该告诉您的应用使用该路由器。

    所以,如果你有一个像 loginRouter.js 这样的文件,它的内容如下:

    const router = new express.Router();
    
    router.get('/api/login', auth, (req, res) => {
        try {
            res.send(<whatever>);
        } catch (e) {
            res.status(500).send(e);
        }
    });
    
    module.exports = router;
    

    然后,在 app.js 中,你必须导入它

    const loginRouter = require('./routers/login');
    

    并使用 .use 方法将其应用到 app.js,如下所示:

    app.use(loginRouter);
    

    希望这是您无法从前端访问该端点的唯一原因!

    【讨论】:

    • 感谢您的建议。我收到了同样的错误。是否有其他文件可以与您分享,或者我们可以通过其他应用程序(discord、google duo、zoom 等)实时交谈。@Maximiliano Poggio
    • 我会赞成这一点,因为添加: app.use(loginRouter) 是必要的,正如您在给定用例的情况下所建议的那样。此外,如答案中所述,React 需要代理与后端进行通信以获取非静态资产。
    【解决方案2】:

    为了让 React 前端与 Express 后端通信,我必须配置代理。我打开了 React 的 package.json 并添加了这样的“代理”行:

    {
      "name": "bible-app",
      "version": "0.1.0",
      "private": true,
      "proxy": "http://localhost:9000",
    . 
    .
    .
    }
    

    “代理”行中的端口 (9000) 必须与您的 Express 服务器运行的端口相匹配。因此,每当 React 应用程序向非静态资源(基本上不是图像、CSS 或 index.html)发出请求时,它都会将请求转发到“代理”中指定的服务器。

    来源:https://daveceddia.com/create-react-app-express-backend/

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 2022-06-22
      • 2017-02-28
      • 2020-12-10
      • 1970-01-01
      • 2019-05-01
      • 2021-09-27
      • 2018-11-03
      • 1970-01-01
      相关资源
      最近更新 更多