【问题标题】:Cannot GET from endpoint in Express.js无法从 Express.js 中的端点获取
【发布时间】:2020-08-01 12:08:59
【问题描述】:

我的 express 应用程序中有两个端点,一个是 /ping - 不带任何参数并且工作正常,另一个是 /posts,它带有一个强制参数“tag”和两个可选参数“sortBy”和“direction” .

应用程序启动,在 Postman 中 /ping 在 GET 上运行良好,但 /posts 没有按预期运行

const express = require('express')
const apicache = require('apicache')
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 8080; //use 8080 or use whatever Heroku gives you
const { ping, getPosts } = require('./controller')

const app = express()
//app.use(express.json())
app.use(bodyParser.json())
const cache = apicache.middleware; //as described on https://www.npmjs.com/package/apicache

app.get('/api/ping', ping) //the first requirement, a ping endpoint


app.get('/api/posts/:tag/:sortBy?/:direction?', cache('5 minutes'), getPosts) //second requirement, an endpoint that fetches posts from the hatchways website

app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`)
})

现在根据 Express 的文档,我希望 url "localhost:8080/api/posts?tag=tech" 可以工作,但是 Postman 说不能 GET /api/posts 起作用的是点击 URL“localhost:8080/api/posts/tag/tech”,这不是这个应用程序应该响应的。

我想我遗漏了一些关于 URL 规范的内容。我确实需要它在“localhost:8080/api/posts?tag=tech”上工作 并不是 "localhost:8080/api/posts/tag/tech"

感谢您的帮助,谢谢。

【问题讨论】:

    标签: node.js express url postman


    【解决方案1】:

    您似乎对查询和路由参数有些困惑。

    查询是 URL 的一部分,它看起来像这样:

    https://example.com/api/posts?tag=tech&this=that+something
    

    虽然路由参数(有点)相似,但它们并不相同。它看起来像一个常规 URL,但它的某些部分可能会有所不同。

    目前,您正在定义您的快速路由以接受route parameters,而不是queries。要使其适用于查询,只需执行以下操作:

    // Remove the 3 route parameters, and do this instead.
    app.get('/api/posts', cache('5 minutes'), getPosts);
    

    并且,请确保在 getPosts 控制器中使用 req.query

    exports.getPosts = function(req, res) {
      // Get whatever you need in req.query
      // In your case you need tag, sortBy, and direction.
      const { tag, sortBy, direction } = req.query;
    
      // You API code.
    }
    

    现在,您的 express API 应该可以正常运行了。

    【讨论】:

    • 是的,在看到 15 分钟没有答案后,我们就这样做了!干杯
    • @ashishparalkar 您可能希望将此标记为答案,以便将其标记为已解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多