如何在 Javascript/NodeJS 中将两个参数传递给 API“获取”请求

Mat*_*ton 0 mongodb node.js next.js swr

我有一个 React 组件,它必须对 MongoDB 数据库执行带有两个参数的 find({}) 查询。

const likes = await Likes.find({ postId: postId, userId: userId }).exec()
Run Code Online (Sandbox Code Playgroud)

由于 Mongo 代码只能在服务器上运行,所以我必须进行 API 调用(我正在使用 NextJS)。这个API调用显然是一个GET请求。如何使用 SWR(或 fetch)将“postId”和“userId”传递给获取请求?

我试图将它们作为对象通过“身体”传递,但我认为这根本不是正确的方法。

const likesPerUser = {
    postId: postId,
    userId: userId
}

const docs = await fetch('/api/likes/user', {
    method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
    body: JSON.stringify(likesPerUser),
})
Run Code Online (Sandbox Code Playgroud)

我无权访问 URL 查询字符串

我有一种感觉,我可能有点跑题了。任何帮助将非常感激。干杯,马特

Sha*_*bin 5

带有查询参数的解决方案

query params您可以传递GET 请求 URL 中的参数。

以下是具有多个查询参数的 URL 的格式:

http://localhost:8000/api/likes/user?postId=xyz&userId=123
Run Code Online (Sandbox Code Playgroud)

在这里,您可以看到?表示查询参数已启动的符号。而且,您还会注意到&用于分隔多个查询参数。这样,您可以发送任意数量的查询参数。

注意:所有查询参数都是string. URL 中的查询参数大小最多可为1024 个字符。

以下是从以下位置接收查询参数的示例代码node.js backend

exports.sampleFunction = async (req, res) => {
    const postId = req.query.postId
    const userId = req.query.userId

    // write your code here
}

Run Code Online (Sandbox Code Playgroud)

以下是从using发送查询参数的示例代码:front-endfetch

const docs = await fetch(`/api/likes/user?postId=${postId}&userId=${userId}`, {
    method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
})
Run Code Online (Sandbox Code Playgroud)