【发布时间】:2021-08-10 22:39:00
【问题描述】:
如果这是一个愚蠢的问题,我很抱歉,但我是这个“后端工作”的新手。我在下面有这段代码,问题是每当我调用 fetchSum() 时,数据都会成功发送到服务器,但是当它返回客户端时,它会给我这个错误。 JSON中位置0的意外令牌
NUXT.JS
<script>
export default {
data() {
return {
sumInput: '',
regInput: 'EUNE',
summonerSearched: '',
loadedSummoner: ''
};
},
methods: {
async fetchSum() {
fetch('http://localhost:3001', {
method: 'POST',
headers: {
'Content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
summoner: this.sumInput,
region: this.regInput
})
});
this.loadedSummoner = await fetch('http://localhost:3001/loadedSum', {}).then(t => t.json());
console.log(this.loadedSummoner.summoner);
}
}
};
</script>
和快递
const express = require('express');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 3001;
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser());
let summoner;
app.post('/', async (req, res) => {
summoner =
req.body;
console.log(summoner);
});
app.get('/loadedSum', (req, res) => {
res.json(summoner);
});
app.listen(PORT, () => {
console.log('Server is running on port ' + PORT);
});
【问题讨论】:
-
你为什么在等待 req.body?
-
我认为没有它,它无法获取数据,因为它没有在那里传递,但这不是问题。
标签: javascript node.js vue.js nuxt.js