2017-05-04 182 views
2

我想用愛可信發佈自己的狀態,但我不能使用expressjsVue公司JS 2 Axios公司POST請求 - 表格

這是我在做什麼來獲取數據到我的後端:

<template> 
<form class="" method="post" @submit.prevent="postNow"> 
<input type="text" name="" value="" v-model="name"> 
<button type="submit" name="button">Submit</button> 
</form> 
</template> 

export default { 
    name: 'formPost', 
    data() { 
    return { 
     name: '', 
     show: false, 
    }; 
    }, 
    methods: { 
    postNow() { 
    axios.post('http://localhost:3030/api/new/post', { 
    headers: { 
     'Content-type': 'application/x-www-form-urlencoded', 
    }, 
    body: this.name, 
    }); 
    }, 
    components: { 
    Headers, 
    Footers, 
    }, 
}; 

後端文件:

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 
router.post('/new/post', (req, res) => { 
    res.json(console.log("this is working" + ' ' + req.body.name)); 
}); 

我收到的錯誤是:

this is working undefined 
+1

'posti'不被任何定義,這裏使用'體:this.posti ' – wostex

+0

對不起,我更新了我的問題,應該是this.name – Marketingexpert

+0

哦,我剛剛注意到:你的方法不在'methods'對象內。把它放在'方法'裏面,還有'data','components'等。 – wostex

回答

6

愛可信post格式:

axios.post(url[, data[, config]])

你的要求應該是:

axios.post('http://localhost:3030/api/new/post', 
    this.name, // the data to post 
    { headers: { 
     'Content-type': 'application/x-www-form-urlencoded', 
     } 
    }).then(response => ....); 

小提琴:https://jsfiddle.net/wostex/jsrr4v1k/3/

+1

This Works! thnx很多,我真的很感激你的時間:) thnx了! – Marketingexpert