在 API 路由中使用变量时无法在 FaunaDB 中获取数据

Can't fetch data in FaunaDB when using variable in API route

我有一条 API 路线,并且有效:

import { query as q } from 'faunadb';
    
export default async (req, res) => {
    try {
        const customer = await guestClient
            .query(q.Get(q.Match(q.Index('user_by_username'), "feronimo")))
            .catch((err) => console.error('Error: %s', err));
    
        res.status(200).json(customer.data);
        console.log(customer.data + 'cd');
        console.log(customer + 'c');
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
};

我的用户名是“feronimo”,它在我输入时出现。但是,我必须将其视为变量。 我用 useSWR:

发送变量
const fetcher = (params) => (url) => post(url, params);
    
const { data: info, error } = useSWR(
    `/api/profilepages`,
    fetcher({ key: username }) /* {
        dedupingInterval: 1000000
    } */
);

正在返回 { username: 'feronimof' }

export default async (req, res) => {
    const username = req.body;

    const u = username.username;
    try {
        const customer = await guestClient
            .query(q.Get(q.Match(q.Index('user_by_username'), u)))
            .catch((err) => console.error('Error: %s', err));

        res.status(200).json(customer.data);
        console.log(customer.data + 'cd');
        console.log(customer + 'c');
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
};

这个returns[object Object].

在这种情况下,您可以使用动态 API 路由,例如 pages/api/profilepages/[username].js。这允许您在针对变量发出请求时传递变量。

// In your component code that makes the request

const { data: info, error } = useSWR(
    `/api/profilepages/${username}`,
    fetcher()
);
// pages/api/profilepages/[username].js

export default async (req, res) => {
  const u = req.query.username; // This would return the username you sent

  // Your API logic here
};