学习如何使用 Sapper。我有一个带有表单的组件(表单有一个输入电子邮件地址的字段)并使用 fetch 将数据发布到服务器句柄。当我发布数据并尝试记录我发布的数据时,它会记录未定义。我不知道为什么,需要帮助才能弄清楚。
这是我的表单组件并获取邮政编码:
<script>
let emailvalue
let url = "posthandle"
async function handleSubmit(event) {
console.log(event);
console.log(event.target);
emailvalue = event.target.email.value;
console.log("this is from the variable--data--:" + content)
// ******** Here is the Fetch() code
fetch(url, {
method: 'POST',
body: JSON.stringify(emailvalue),
headers: {
'Content-Type': 'application/json'
}
})
.then(r => {
//this is gives the error that res stream is locked console.log(r.json())
consolde.log(r)
r.json()
.then(function(result) {
// this logs [object object]
console.log("let us see" + result)
})
})
.catch(err => {
// POST error: do something...
console.log('POST error', err.message)
})
//post code example https://stackoverflow.com/questions/55393685/js-sapper-posting-data-to-server-the-right-way
}
</script>
<p> {emailvalue} </p>
<form on:submit|preventDefault="{handleSubmit}">
<label for="email">Email</label>
<input required type="email" id="email" />
<button type="submit">Create account</button>
</form>
显示为:console.log("let us see" + result) 的行显示 [object Object],我不明白为什么?
我管理帖子的句柄:
export async function post(req, res, next) {
res.setHeader('Content-Type', 'application/json')
/* Retrieve the data */
var data = req.body;
// Do something with the data...
// it logs Undefined. Why?
console.log("Here's the posted data:" + data );
/* Returns the result */
return res.end(JSON.stringify({ success: true }));
}
为什么数据未定义?代码错了吗?我应该做些什么来阅读“数据”并管理表单中发布的实际数据吗?
这是我的服务器代码(在@J之后)指出了正文解析器问题:
import express from 'express';
import * as sapper from '@sapper/server';
const sirv = require('sirv');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const session = require('express-session');
const assets = sirv('static', {
maxAge: 31536000, // 1Y
immutable: true
});
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
app.use(assets, sapper.middleware()).listen(process.env.PORT, err => { if (err) console.log('error', err); });
如果我从具有响应的 fetch 函数中获得 console.log (r)。我在控制台中得到这个:响应{type:“basic”,url:“ http://localhost:3000/posthandle ”,redirected:false,status:200,ok:true,...}