JS Sapper : posting data to server (the right way ?)
Asked Answered
D

2

9

How to properly post data to server using Sapper JS lib ?

Saying : I have a page 'board-editor' where I can select/unselect tiles from an hexagonal grid written in SVG, and adds/substract hex coordinates in an store array.

Then user fills a form, with board: name, author, and version... Clicking on save button would POST the form data plus the array in store. The server's job, is to store the board definition in a 'static/boards/repository/[name].json' file.

Today, there's few details on the net to use correctly Sapper/Svelte with POSTing data concerns.

How to proceed ? Thanks for replies !

EDIT:

to avoid reposting of the whole page, which implies to loss of the app state, I consider using a IFRAME with a form inside.... but how to init a copy of sapper inside the IFRAME to ensure I can use the this.fetch() method in it ?

Diphyllous answered 28/3, 2019 at 9:4 Comment(0)
K
16

I use Sapper + Svelte for a website, it's really amazing! In my contact form component, data are sent to the server. This is how it's done without iframe. The data sent and received is in JSON format.

On the client side (component):

var data = { ...my contact JSON data... }
var url = '/process/contact' // associated script = /src/routes/process/contact.js

fetch(url, {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(r => {
  r.json()
    .then(function(result) {
      // The data is posted: do something with the result...
    })
})
.catch(err => {
  // POST error: do something...
  console.log('POST error', err.message)
})

On the server side:

script = /src/routes/process/contact.js

export async function post(req, res, next) {
  /* Initializes */
  res.setHeader('Content-Type', 'application/json')
  /* Retrieves the data */
  var data = req.body
  // Do something with the data...
  /* Returns the result */
  return res.end(JSON.stringify({ success: true }))
}

Hope it helps!

Kneehole answered 3/6, 2019 at 9:11 Comment(9)
Jack: Thanks for sharing. Very helpful. Question: are you using Polka server or Expressjs server?Formally
Marco: ExpressJS server. Polka is fine, but Express is the most used: npmtrends.com/polka-vs-expressKneehole
Jack, sorry to bother you again but after reading for few days on the topic, I'm confused. How the contact.js code is served by the server? I used expressjs many times, the routes handle matches with code on the front but here the post handle in contact.js which is not part of the server file. correct? I'm new to svelte and sapper. Trying to use them.Formally
Marco: Unlike a purely Express app, Sapper handles routing for you. You don't have to set the routing in the server.js file. All the files you put in the /src/routes folder are routes.See: sapper.svelte.dev/docs#RoutingKneehole
Thank you so much. Built an example and it worked. Tremendous explanation on your part. I appreciate it.Formally
Do I need to install body-parser and import it into server.js or the route handle js file to read and access the data posted in your example that you posted?Formally
I tried your code but when I try to console.log(data) in the route handle, it gives me undefined?Formally
I posted a question so we don't have to use the comment section here. If you feel generous with your time, please take a look and let me know how to get it to work. Thanks #58128104Formally
Jack, if you could post a server.js file with all the correct setup so I make sure my server has all the right packages installed. Thank you for your help.Formally
S
12

Together with the solution above, you might get undefined when you try to read the posted data on the server side.

If you are using the standard degit of Sapper you are using Polka. In order to enable body-parse in Polka you can do the following.

npm install body-parser

In server.js, add the following

const { json } = require('body-parser');

And under polka() add imported

.use(json())

So that it in the end says something like

...
const { json } = require('body-parser');

polka() // You can also use Express
    .use(json())
    .use(
        compression({ threshold: 0 }),
        sirv('static', { dev }),
        sapper.middleware()
    )
    .listen(PORT, err => {
        if (err) console.log('error', err);
    });
Sines answered 27/12, 2019 at 12:4 Comment(1)
Thank you very much. I spent one full afternoon to make the post method work. I was going crazy and that was the issue. Really can't understand why the Sapper team made Polka as the standard without including such a fundamental configuration to use the post method.Rosenblum

© 2022 - 2024 — McMap. All rights reserved.