我已经成功完成了本教程:
https://medium.com/p/a69845ace489/responses/show
现在,如何使用vue axios从dist目录向我的server.js节点文件进行ajax调用?
因为heroku通过process.env.PORT为我的连接提供了随机端口。
这是我在main.js中的服务器配置,位于vue.js应用程序中,位于dist目录中:
Vue.server = Vue.prototype.server = "https://myapp.herokuapp.com/";
请注意,没有端口,因为我不知道heroku使用哪个端口。
这是来自vue.js应用的axios随机调用
axios.post(Vue.server + "getUser", {id: this.id})
.then(response => {
this.user = response.data;
})
.catch(function (erreur) {
console.log(erreur);
});
这是我的server.js文件:
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
app.listen(port);console.log('server started '+ port);
我的问题是无法在我的vue应用程序中设置端口,其余所有代码均在工作,我不包括节点其余的东西。
您是否认为将localhost作为Vue.server变量可以在线运行?谢谢
第2部分 :
像这样更改了我的server.js文件,添加了一个getUsers发布Web服务:
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
const mongodb = require("mongodb");
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 80;
const cors = require("cors");
app.use(cors());
app.post("/getUsers", function(req, res) {
res.send('ok');
});
app.listen(port);
console.log('server started '+ port);
这是我的Helloworld.vue现在:
import axios from "axios";
axios.defaults.withCredentials = true;
export default {
name: 'HelloWorld',
props: {
msg: String
},methods: {
getUsers: function () {
axios
.post("http://localhost/" + "getUsers", {
})
.then(response => {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
},
created: function () {
this.getUsers();
}
}
</script>
2.5:在我的本地主机服务器上,一切运行良好,ajax调用完全没有CORS错误运行:
node server.js
git push heroku主
跨域请求被阻止:同源策略禁止读取位于http:// localhost / getUsers的远程资源。(原因:CORS请求未成功)。
您的代码当前已将POST位置硬编码为localhost
,这保证不能在heroku(或与此有关的任何其他托管服务)上运行。
取而代之的是,甚至不用硬编码“正确的域”,只需直接POST到/getUsers
,而无需任何显式域,并且无论您使用哪个域(命名的IP,WLAN,LAN,就可以了)。