Reputation: 347
I have followed this tutorial with success :
https://medium.com/p/a69845ace489/responses/show
Now, how can I do an ajax call from my dist directory using vue axios, to my server.js node file ?
Because heroku is giving randoms ports to my connexion with process.env.PORT.
This is my server config in main.js, inside the vue.js app, inside the dist directory :
Vue.server = Vue.prototype.server = "https://myapp.herokuapp.com/";
Please notice that there is no port, cause i can't know which port is used by heroku.
This is an axios random call, from the vue.js app
axios.post(Vue.server + "getUser", {id: this.id})
.then(response => {
this.user = response.data;
})
.catch(function (erreur) {
console.log(erreur);
});
This is my server.js file :
// 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);
My problem is that the port cant be set in my vue app, all of the rest of the code is working, i dont include the node rest stuff.
Do you think that keeping localhost as a Vue.server variable would work online ? Thank you
PART 2 :
Changed my server.js file like this , added a getUsers post web service :
// 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);
This is my Helloworld.vue now :
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 : on my localhost server, all is working well, the ajax call is working with no CORS error at all :
node server.js
git push heroku master
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/getUsers. (Reason: CORS request did not succeed).
Upvotes: 1
Views: 379
Reputation: 53588
Your code currently has the POST location hardcoded to localhost
, which is guaranteed to not work on heroku (or any other hosting service for that matter).
Instead, don't even hardcode "the correct domain", just POST directly to /getUsers
, without any explicit domain, and the browser will do the right thing regardless of the domain you're on (named, plain IP, WLAN, LAN, it'll just work).
Upvotes: 1