JS Sapper:将数据发布到服务器(正确的方法?) [英] JS Sapper : posting data to server (the right way ?)

查看:150
本文介绍了JS Sapper:将数据发布到服务器(正确的方法?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Sapper JS lib将数据正确发布到服务器?

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

说:我有一个板编辑器"页面,可以在其中从SVG编写的六边形网格中选择/取消选择图块,并在存储数组中添加/减去十六进制坐标.

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.

然后,用户填写一个表单,其中包括:名称,作者和版本...单击保存按钮将发布表单数据以及存储中的数组.服务器的工作是将电路板定义存储在"static/boards/repository/[name] .json"文件中.

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.

今天,网上很少有细节可以正确使用Sapper/Svelte来处理数据发布问题.

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

如何进行?感谢您的答复!

How to proceed ? Thanks for replies !

为避免重新发布整个页面(这意味着丢失应用程序状态),我考虑使用IFRAME,其中包含一个表单....但是如何在IFRAME中初始化sapper的副本以确保我可以使用里面有this.fetch()方法吗?

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 ?

推荐答案

我在网站上使用Sapper + Svelte,真是太神奇了!在我的联系表单组件中,数据被发送到服务器.这是没有iframe的情况.发送和接收的数据为JSON格式.

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.

在客户端(组件):

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

在服务器端:

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

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

希望有帮助!

这篇关于JS Sapper:将数据发布到服务器(正确的方法?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆