Home > Blockchain >  How can I change the Axios responseURL when connecting a Vue.js frontend with a Node.js backend?
How can I change the Axios responseURL when connecting a Vue.js frontend with a Node.js backend?

Time:12-27

I am trying to connect a Vue.js frontend to a Node.js backend using Axios. I followed tutorials online and have the following code snippets:

In backend, I have the following Node.js code snippet to post to localhost:5000/signup :

app.post("/signup", (req, res) =>{ // receive form data from signup
  console.log("Hello");
})

I am listening to port 5000:

const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => {
  console.log("Server is running on port", server.address().port);
});

Frontend code snippets look something like this:

  methods: {
    submit() {
      this.$v.$touch();
      axios.post("/api/signup", {
        fname: this.fname,
        lname: this.lname,
        email: this.email,
        password: this.password,
        gender: 'Male',
        dob: this.dob,
      }).then((res) => {
        if(res.data.msg === "Email exists"){
          console.log("Email exists")
        }
        else{
          this.$router.push({ path: './browsing' });
        }
      })
      // .catch(()=>{
      //   alert("Something Went Wrong");
      // })      
      

    },
    clear() {
      this.$v.$reset()
      this.name = ''
      this.email = ''
      this.select = null
      this.checkbox = false
    },
  }

I expected the Axios responseURL in the console to send me to localhost:5000/signup and print "Hello" but I have the following error message:

responseURL
: 
"http://localhost:8081/api/signup"

It sends me to localhost:8081 which is the default port for Vue and DOESN'T PRINT ANYTHING. What could be the reason for this? And how can I make my responseURL localhost:5000/signup?

CodePudding user response:

You're setting the port as process.env.PORT or 5000. So if process.env.PORT constains a non falsy value it will use process.env.PORT instead of 5000.

A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false of course.

Try to update your code to const PORT = 5000;.

CodePudding user response:

After playing around, I found that the problem was me not requiring "cors" in the backend file.

All I added was:

var cors = require('cors')
var app = express()
app.use(cors())
  • Related