【问题标题】:How do I query with url parameter?如何使用 url 参数进行查询?
【发布时间】:2021-06-17 02:56:47
【问题描述】:

我是 Node.js 的新手,并尝试通过从 iOS 应用程序将电子邮件作为 url 参数发送来检查电子邮件是否已被接收。它不工作,不知道我做错了什么。

我无法 console.log 从前端发送的 VSCode 中的电子邮件参数,它确实在 XCODE 中打印(http://localhost:3000/api/user/email/test@gmail.com )并且我知道后端正在获取 GET 请求。

我的路由器代码是:

const express = require(`express`)
const router = new express.Router()
const User = require(`../models/user-model`)   //  import User model

router.get(`/api/user/email/:email`, async (req, res) => {
    console.log(req.params) // does NOT print email: test@gmail.com
    try {
        const user = await User.findOne(req.params.email)

        if (user) {
            console.log(user._id)
            res.send({ available: false })
        } else {
            res.send({available: true})
        }
    } catch {
        res.status(404).send()
    }
})

谢谢!

【问题讨论】:

  • "不打印电子邮件:test@gmail.com" — 虽然知道什么时候没有发生预期的行为总是有用的,但你真的应该告诉我们你得到了什么行为。它是否打印undefined{}?还有什么?这条线永远不会被调用吗?
  • 您如何将路由器安装到您的应用程序中?考虑到这一点,您的网址是否真的正确?
  • @Quentin,看起来目标路由没有被调用(我添加了一个 console.log('email route') 并且它没有记录)所以我需要查看我的 Swift代码并仔细检查一切......
  • 忽略 swift 代码。要么没有向http://localhost:3000/api/user/email/test@gmail.com 发出请求(在这种情况下,使用浏览器手动触发请求)要么是错误的 URL(请参阅我之前的评论)。
  • 呃,我忘了添加 'module.exports = router' !我的错!

标签: javascript node.js


【解决方案1】:
         const express = require(`express`)
     const app = new express();
     app.get(`/api/user/email/:email`, async (req, res) => {
     console.log(req.params) // does NOT print email: test@gmail.com
     try {
     // const user = await User.findOne(req.params.email)
     const user = {_id:123};
     if (user) {
        console.log(user._id)
        res.send({ available: false })
     } else {
        res.send({available: true})
     }
     } catch {
     res.status(404).send()
     }
     })

    app.listen(3000,function(){
    console.log("running");
    })

【讨论】:

    【解决方案2】:

    编辑这个..我没有足够的评论..你的路线似乎很好,也许你没有告诉你的应用程序使用这条路线,在开始你的应用程序之前的某个地方你应该有类似的东西:

    this.app = new express();
    ...
    this.app.use('/api', MailRouter); //<=== Adding your required mail route
    ...
    

    我习惯在此处(/api)和路由器(/user/email/:email)中拆分网址。我不确定如何通过将其完全添加到路由器来做到这一点(也许是'/'也许是'')

    【讨论】:

    • 他们没有使用这样的 URL。使用参数的方法没有错。
    • 原来我并没有告诉我的应用使用路线!
    猜你喜欢
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多