我尝试为外部 adobe stock 创建一些 API。 就像标题中一样,我第一次从未定义的链接路由器收到查询,但重新加载页面后它可以正常工作。我的 主页
<Link
href={{
pathname: "/kategoria-zdjec",
query: images.zdjecia_kategoria
}}
as={`/kategoria-zdjec?temat=${images.zdjecia_kategoria}`}
className={classes.button}>
</Link>
和我的服务器
app
.prepare()
.then(() => {
server.get("/kategoria-zdjec", async (req, res) => {
const temat = await req.query.temat;
console.log(temat)
const url = `https://stock.adobe.io/Rest/Media/1/Search/Files?locale=pl_PL&search_parameters[words]=${temat}&search_parameters[limit]=24&search_parameters[offset]=1`;
try {
const fetchData = await fetch(url, {
headers: { ... }
});
const objectAdobeStock = await fetchData.json();
res.json(objectAdobeStock);
const totalObj = await objectAdobeStock.nb_results;
const adobeImages = await objectAdobeStock.files;
} catch (error) {
console.log(error);
}
});
看起来就像下一页上的 getInitialProps
Zdjecia.getInitialProps = async ({req}) => {
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
我认为这是异步造成的问题。
最佳答案
我认为这可能是由于您正在使用 fetch
这实际上是 Web API 的一部分,在服务器上执行时此操作会失败。
您可以使用 isomorphic-fetch这使客户端和服务器之间的 fetch API 保持一致,或者使用 node-fetch当在服务器上调用 fetch 时:
Zdjecia.getInitialProps = async ({ req, isServer }) => {
const fetch = isServer ? require('node-fetch') : window.fetch;
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
关于node.js - 将查询从链接传递到服务器,第一次加载查询值未定义,重新加载后得到正确的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60367073/