Forms 未找到将Vue连接到Express-404的连接

Forms 未找到将Vue连接到Express-404的连接,forms,express,routing,vue.js,Forms,Express,Routing,Vue.js,我正在创建一个简单的应用程序来练习将Vue连接到Express服务器。我有一个表单正试图发送到后端,但似乎无法将数据发送到后端。 我收到的错误是: 邮政404(未找到) 我最好的猜测是我的Vue中的方法在我的服务器上找不到匹配的路由?如果是这样的话,我很困惑,因为我有一个登录的路径 在我的Vue脚本中: const axios = require('axios'); export default { data: function() { return {

我正在创建一个简单的应用程序来练习将Vue连接到Express服务器。我有一个表单正试图发送到后端,但似乎无法将数据发送到后端。 我收到的错误是:

邮政404(未找到)

我最好的猜测是我的Vue中的方法在我的服务器上找不到匹配的路由?如果是这样的话,我很困惑,因为我有一个登录的路径

在我的Vue脚本中:

const axios = require('axios');

export default {
    data: function() {
        return {
          user: {
            email: '',
            password: ''
          }
        }
    },
    methods: {
      sub() {
        var user = {
          email: this.user.email,
          password: this.user.password
        }
        axios.post('/login', user)
          .then(res => console.log(res))
          .catch(err => console.log(err))
      }
    }
}
const path = require('path');
const express = require('express');

const app = express();

app.use(express.static(path.join(__dirname, '..')));

app.post('/login', function(req, res) {
  console.log("Server HIT!!!!!!!!!!!!!!!!!!!!")
})

app.get('*', function (req, res) {
  return res.sendFile('../index.html');
});

app.listen(3000);
console.log('Express server listening on port 3000');
通过后端打开:

const axios = require('axios');

export default {
    data: function() {
        return {
          user: {
            email: '',
            password: ''
          }
        }
    },
    methods: {
      sub() {
        var user = {
          email: this.user.email,
          password: this.user.password
        }
        axios.post('/login', user)
          .then(res => console.log(res))
          .catch(err => console.log(err))
      }
    }
}
const path = require('path');
const express = require('express');

const app = express();

app.use(express.static(path.join(__dirname, '..')));

app.post('/login', function(req, res) {
  console.log("Server HIT!!!!!!!!!!!!!!!!!!!!")
})

app.get('*', function (req, res) {
  return res.sendFile('../index.html');
});

app.listen(3000);
console.log('Express server listening on port 3000');

Express正在vue应用程序以外的其他端口上运行。Vue是标准http,即8080,但express在3000上运行,使用以下代码行:

app.listen(3000);
您正在将请求发送到/login,从前端的角度来看,这是,但express不在这里可用。
基本上,您只需将请求发送到
http://localhost:3000/login
,就这么简单。

默认情况下,express不允许跨原产地请求,即
CORS
。您必须通过设置中间件来启用它。在服务器文件中添加以下行,并且必须在声明任何路由之前添加

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

这是有道理的,不过当我这样做时,我会遇到另一个错误:
XMLHttpRequest无法加载localhost:3000/login。跨源请求仅支持协议方案:http、data、chrome、chrome扩展、https
我添加了http://并将middlewear设置为Ghanshyam Singh在她的帖子中提到的,一切正常。非常感谢。非常感谢。通过我的谷歌搜索,我知道它需要中间件,但我没有意识到它有自己的功能。我正在打我的服务器现在没问题!很高兴帮助您:)