繁体   English   中英

无法从 Express.js 中的端点获取

[英]Cannot GET from endpoint in Express.js

我的 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}`)
})

Now as per Express's docs I would expect the url "localhost:8080/api/posts?tag=tech" to work, however Postman says cannot GET /api/posts What does work is hitting the url "localhost:8080/api/posts /tag/tech”,这不是这个应用程序应该响应的。

我想我缺少关于 URL 规范的一些东西。 我确实需要它在“localhost:8080/api/posts?tag=tech”而不是“localhost:8080/api/posts/tag/tech”上工作

感谢您的帮助,谢谢。

看起来您对查询和路由参数有点困惑。

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

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

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

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

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

并且,确保在getPosts controller 中使用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.
}

现在,您的快递 API 应该符合预期的 function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM