我是Web开发的新手。我想问一下如何使用Nuxt在Axios上创建.post
。
我所需要的只是一个按钮,它将三个输入发送到NodeJS应用。
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<form @submit="formSubmit">
<strong>Name:</strong>
<input type="text" class="form-control" v-model="name">
<strong>Email:</strong>
<input type="text" class="form-control" v-model="email">
<strong>Password:</strong>
<input type="text" class="form-control" v-model="password">
<button class="btn btn-success">Submit</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
name: '',
email: '',
password: ''
};
},
methods: {
//Would like to use the button to do this:
async sendData () {
await this.$axios.get('insert', {
name: this.name,
email: this.email,
password: this.password })
}
}
}
</script>
谢谢您的帮助。
答案 0 :(得分:3)
提交侦听器应改为调用该方法:
<form @submit="sendData">
要发送POST
请求:
this.$axios.post('insert', {
name: this.name,
email: this.email,
password: this.password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
有关更多信息,您可以访问their page。
答案 1 :(得分:1)
您还可以将axios本地导入到您的组件中,并通过以下方式使用它:
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<form @submit="formSubmit">
<strong>Name:</strong>
<input type="text" class="form-control" v-model="name">
<strong>Email:</strong>
<input type="text" class="form-control" v-model="email">
<strong>Password:</strong>
<input type="text" class="form-control" v-model="password">
<button class="btn btn-success">Submit</button>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
name: '',
email: '',
password: ''
};
},
methods: {
//Would like to use the button to do this:
async formSubmit() {
await axios.post('route/url', {
name: this.name,
email: this.email,
password: this.password
})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err)
})
}
}
}
</script>
不要忘记调用formSubmit
方法来实际发出POST
请求。
此外,您的表单似乎没有结束标签</form>
。