【问题标题】:Cannot GET api route (node.js, express)无法获取 api 路由(node.js,express)
【发布时间】:2021-03-11 02:14:18
【问题描述】:

JS 菜鸟,我正在尝试学习有关 node.js API 创建的课程。我正在按照书上的指示做所有事情。这是课程中指定的 server.js 文件:

const http = require('http');
const app = require('./app');

const normalizePort = val => {
  const port = parseInt(val, 10);

  if (isNaN(port)) {
    return val;
  }
  if (port >= 0) {
    return port;
  }
  return false;
};
const port = normalizePort(process.env.PORT || 3000);
app.set('port', port);
const errorHandler = error => {
  if (error.syscall !== 'listen') {
    throw error;
  }
  const address = server.address();
  const bind = typeof address === 'string' ? 'pipe ' + address : 'port: ' + port;
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges.');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use.');
      process.exit(1);
      break;
    default:
      throw error;
  }
};

const server = http.createServer(app);

server.on('error', errorHandler);
server.on('listening', () => {
  const address = server.address();
  const bind = typeof address === 'string' ? 'pipe ' + address : 'port ' + port;
  console.log('Listening on ' + bind);
});

server.listen(port);

我从控制台运行此服务器,当我向 http://localhost:3000/api/stuff(我在 app.js 中指定的路由)发送 get 请求时,cUrl 和邮递员请求给了我 404(无法获取):

const express = require('express');
const app = express();
app.use('http://localhost:3000/api/stuff', (req, res, next) => {
  const stuff = [
    {
      message: "this is a JSON"
    },
    {
      message: "this is also a JSON"
    }
  ];
  res.status(200).json(stuff);
});

我的 package.json 看起来还不错:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "node": "^15.2.1"
  }
}

在 app.js 中我尝试了 app.get 而不是 app.use,并将 JSON 直接生成到 res.status(200).json() 中。

我真的怀疑问题出在 server.js 中,我尝试弄乱它无济于事(提供 normalizePort() 一个字符串而不是一个整数,消除了 process.env.port,简化了它检查是否3000 端口是免费的)。

我当然在 SO 中检查过类似的问题,但似乎没有什么符合我的具体问题。

节点--版本 v13.11.0(课程也是基于旧版本)

【问题讨论】:

  • 你试过app.use('/api/stuff', ...吗?
  • 它有效!

标签: javascript node.js


【解决方案1】:

A URL consists of multiple parts:

  • 方案
  • 权限(包括主机和端口)
  • 路径
  • 查询
  • 片段

解析http://localhost:3000/api/stuff会导致:

  • 方案:http
  • 权限
    • 主机:localhost
    • 端口:3000
  • 路径:/api/stuff

app.use 不需要完整的 URL。它只需要path 部分:app.use('/api/stuff',

您可以传递的不仅仅是一个简单的字符串。示例可以在documentation 中找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2019-09-02
    • 2015-01-03
    • 2021-11-05
    相关资源
    最近更新 更多