我尝试用express在后端更新JSON文件并在前端显示新数据。但目前当我做请求时,我得到了很好的响应,但数据没有改变。
服务器Express (route)脚本编辑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)
})
}
如果我在请求表显示新数据后重启服务器。如果你知道如何在不重启服务器的情况下显示信息,这会对我有很大帮助。
I tried this
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()
})
But I got error
"Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after their sent to client">
从回
和
"[Vue warn]: v-on处理程序(Promise/async)出错:"Error: Request aborted">
从前端
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
您需要返回post
响应的最新JSON,然后将其分配给this.words_init
变量。