Sapper Svelte Blog get Data from Server

271 views Asked by At

i m having problems getting Sapper expample blog to work with getting real data from the a data base. In the Example the data is served from a js file. I tried to replace the data with my own, fetching is from the server like so in the _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;


})()

but it gives me this error

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)

I have to admit that i am pretty new to sapper and svelte and maybe i don t have a proper understanding of how the slug thing really works. any help appreciated

1

There are 1 answers

1
Rich Harris On BEST ANSWER

An async function always returns a promise — when you see posts$1.map is not a function, that's because the promise doesn't have a map method (and if it did, it wouldn't be what you wanted).

Basically, you'll need to await that promise in route handlers that need that data:

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));
}