如何解决在 API 路由中使用变量时无法在 FaunaDB 中获取数据
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 });
}
};
这将返回 [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
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。