2017-08-03 169 views
0

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

POST http://localhost:8080/login 404 (Not Found)

我最好的猜测是,在我的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'); 

回答

0

默认情况下,明文不允许跨源请求,即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(); 
}); 
+0

谢谢!从我的谷歌搜索中,我知道它需要中间件,但我没有意识到它进入了它自己的功能。我打我的服务器现在没有问题! – Ziyal

+0

很高兴帮助你:) –

3

Express的另一个端口比你VUE的应用程序上运行。 Vue公司是标准的http这是8080,但快递运行在3000这一行:

app.listen(3000); 

您将请求发送到/登录,这一现象从您的前端点是http://localhost:8080,但是这不是地方快递可用。 基本上所有你需要做的就是发送请求到http://localhost:3000/login,就这么简单。

+0

有道理之前,虽然当我这样做,我得到另一个错误:'的XMLHttpRequest无法加载本地主机:3000 /登录。交叉来源请求仅支持协议方案:http,data,chrome,chrome-extension,https' – Ziyal

+0

不好意思,当然是http:// localhost之前。 –

+0

我添加了http://,并将她的帖子中提到的Ghanshyam Singh设置为中间服装,一切都很好。谢谢! – Ziyal

相关问题