首页 > 解决方案 > 如何正确配置我的后端以便从我的表单接收数据?我正在使用 Vue.js

问题描述

我的目标是使用 nodemailer 发送电子邮件,因此我需要从后端执行此操作。我的 vue 组件中有一个表单,我正在尝试将数据发送到 http://localhost:3000/ 但出现错误:POST http://localhost:3000/ 404 (Not Found)。我正在使用 Axios 来做到这一点。当我发出 get 请求时,我得到了没有任何错误的响应,但我无法发出 post 请求。首先,我创建了一个服务器,只是为了在 heroku 上部署我的网站(响应建议),但现在我不确定我的后端配置是否可以从我的客户端接收数据。我环顾四周,但没有找到问题的具体答案。

联系方式:

<form class="form" @submit.prevent="sendData">
                <ul>
                    <li>
                        <label for="name">Name</label>
                        <input type="text" id="name" name="user_name" v-model="name">
                    </li>
                    <li>
                        <label for="mail">E-mail</label>
                        <input type="email" id="mail" name="user_email" v-model="email">
                    </li>
                    <li>
                        <label for="msg">Message:</label>
                        <textarea id="msg" name="user_message" v-model="message"></textarea>
                    </li>
                </ul>
                <button type="submit" class="btn">Send</button>
            </form>




    <script>
import * as axios from 'axios';
export default {
    data(){
        return{
            name: "", 
            email: "", 
            message: ""
        }
    },
    methods: {
       sendData(){
           console.log(this.name, this.email,this.message);
           axios.post("http://localhost:3000/",{
               name: this.name,
               email: this.email,
               message: this.message
           })
         .then(response => {
            console.log(response)
         })
         .catch(error =>{
            this.error = error;
         }) 
       }
    }
}
</script>

我的 server.js:

const express = require('express');
const port = process.env.PORT || 3000;
var cors = require('cors')
const app = express();
app.use(cors())

app.use(express.static(__dirname + "/dist/"));

app.get("/", function(req, res) {
    res.sendfile(__dirname + '/dist/index.html'); 
})


app.listen(port);

console.log('Server started...');

标签: vue.js

解决方案


您正在向 发送POST请求http://localhost:3000/,但这GET在您的服务器中设置为 a。所以试试:

app.post("/", function(req, res) {
    res.sendfile(__dirname + '/dist/index.html'); 
})

推荐阅读