我正在尝试使用axios发布表单。但这不起作用(我无法将数据发送到后端)。很抱歉,我是vue js的新手。
这就是我在做什么:
模板:
<b-form @submit.prevent="create" method="post">
<b-form-group>
<b-col sm="1">
<label :for="`type-text`">Title:</label>
</b-col>
<b-col sm="9">
<b-form-input :id="`type-text`" :type="text" v-model="article.title" required></b-form-input>
</b-col>
</b-form-group>
<b-form-group>
<b-col sm="1">
<label for="textarea-no-auto-shrink">Content:</label>
</b-col>
<b-col sm="9">
<b-form-textarea id="textarea-no-auto-shrink" placeholder="write something..." v-model="article.content" required rows="3" max-rows="3"></b-form-textarea>
</b-col>
</b-form-group>
<b-form-group>
<b-col sm="1">
</b-col>
<b-button type="submit" class="mt-2 ml-3">Submit</b-button>
</b-form-group>
</b-form>
脚本
import axios from 'axios'
export default {
name: 'List',
props: {},
data() {
return {
articles: [],
article: {
title: '',
content: '',
}
}
},
mounted() {
axios
.get('http://127.0.0.1:8000/api/')
.then(response => (this.articles = response.data))
.catch(error => console.log(error))
},
methods: {
create() {
axios
.post('http://127.0.0.1:8000/api/',
this.article
)
.then(response => {
this.$router.push('/home');
return response;
})
.catch(error => console.log(error))
}
},
}
</script>
错误:
无法加载资源:服务器以状态
403
进行了响应 (禁止)
答案 0 :(得分:0)
我现在使用 Vue.js 和 Node.js 在我的项目中工作。我将向您展示我的发布请求。它工作正常。后端架构为Model,Route,Controller
这是前端的post请求:
handleSubmit() {
const create = {
name: this.name,
description: this.description,
imageUrl: this.imageUrl,
};
axios
.post("http://localhost:3000/api/category", create)
.then((res) => {
console.log(create);
console.log(res);
})
.catch((err) => {
console.log(err);
});
},
这是后端的post请求处理:
exports.storeCategory = async function (req, res) {
const createCategory = new category({
name: req.body.name,
description: req.body.description,
imageUrl: req.body.imageUrl,
});
try {
const savecategory = await createategory.save();
res.send(create);
} catch (err) {
res.send(err);
}
};
答案 1 :(得分:-1)
我认为您的后端无法识别您用于发布请求的端点。 也许您想点击“ http://127.0.0.1:8000/api/posts”之类的内容?
此外,axios的有效负载应该是具有键值对的对象
axios
.post('http://127.0.0.1:8000/api/posts',
{article: this.article}
)
.then(response => {
this.$router.push('/home');
return response;
})
.catch(error => console.log(error))