在使Sapper示例博客无法从数据库中获取真实数据时遇到了问题。在示例中,数据是通过js文件提供的。 我试图用自己的数据替换数据,就像在_post.js
中那样从服务器获取数据import fetch from "node-fetch";
export default (async () => {
const response = await fetch('https://www.exampleserver.de/posts?id=1309');
let json = await response.text();
//json = JSON.parse(json);
posts = json;
return posts;
})()
但是它给了我这个错误
TypeError: posts$1.map is not a function
at Object.<anonymous> (/Users/mark/01_m_code/01 SVELTE SAPPER/04 blog/__sapper__/dev/server/server.js:43:41)
我必须承认,我对工匠和苗条还很陌生,也许我对the的东西是如何工作的没有正确的了解。任何帮助表示赞赏
答案 0 :(得分:0)
async
函数总是返回一个诺言—当您看到posts$1.map is not a function
时,这是因为诺言没有map方法(如果有,则不是您想要的)
基本上,您需要await
在需要该数据的路由处理程序中作出承诺:
import posts_promise from './_posts.js';
export async function get(req, res) {
const posts = await posts_promise;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(posts));
}