【发布时间】:2021-10-20 13:06:44
【问题描述】:
我尝试在后端使用 express 更新 JSON 文件并在前端显示新数据。但目前,当我提出请求时,我得到了很好的响应,但数据没有改变。
Server Express(路由)脚本编辑 JSON:
function editJSON(fr,en,es){
var obj = {
list_words: []
}
fs.readFile('./assets/words.json', 'utf-8', (err, jsonString) =>{
if(err){
console.log(err)
}else {
try{
obj = JSON.parse(jsonString)
obj.list_words.push({fr: fr, en: en, es: es})
json = JSON.stringify(obj)
fs.writeFileSync('./assets/words.json',json,'utf-8',function (err){
if (err) throw err;
console.log('complete');
})
} catch (err){
console.log(" Error parsing JSON", err)
}
}
})
}
下面的脚本发送数据和其他显示。
methods: {
async addWord () {
var obj = {
fr: this.words_input.fr,
en: this.words_input.en,
es: this.words_input.es
}
const res = await axios.post('http://localhost:3000/addwords', obj)
const data = res.data
console.log(data)
}
},
mounted: async function () {
await axios.get('http://localhost:3000/words.json')
.then(response => {
this.words_init = response.data
})
.catch(error => {
console.log('There was an error: ' + error.response)
})
}
如果我在显示带有新数据的请求表后重新启动服务器。如果您知道如何在不重新启动服务器的情况下显示信息,这对我很有帮助。
我试过了
const res = await axios.post('http://localhost:3000/addwords', obj)
const data = res.data.list_words
this.words_init = data
这条路线
app.post('/addwords',(req,res)=>{
console.log(req.body.fr)
const fr = req.body.fr
const en = req.body.en
const es = req.body.es
editJSON(fr,en,es)
console.log(fr)
res.send(words)
res.status(201).send('created User')
res.end()
})
但我有错误
“错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头”
从后面
和
“[Vue 警告]:v-on 处理程序中的错误(承诺/异步):“错误:请求中止”
从前端
const res = await axios.post('http://localhost:3000/addwords', obj)
this.words_init = res.data.list_words
```
with this route everything work But mu new list don't display
【问题讨论】:
-
我想你希望你的前端在“/addwords”请求之后更新。您的“addWord”方法除了发送请求之外什么都不做,因此您的前端不会做出反应。 “已安装”函数仅在您的组件首次安装时被调用,因此您没有更新前端的机制。一种方法是将您的 json 作为“/addwords”的响应发送并在您的前端处理数据。
标签: javascript vue.js express