databasepostaxiosconnection

getting [AxiosError: Network Error] when calling the server


I am trying to establish a connection using axios between client and server, the server side code is like this: in its index.js file, i am calling routes like this:

app.use("/api/v3", routes);

where routes file is like this:

const express = require("express");
const { Router } = express;
const router = Router();
const userRoutes = require("./User");
router.use("/users", userRoutes);
module.exports = router;

and my userRoutes is like this:

router.post("/signup", async (req, res) => {      try {
    const { username, email, password, firstName, lastName } = req.body;
    const { user, token } = await createUser(
      username,
      email,
      password,
      firstName,
      lastName
    );
    res
      .status(200)
      .json({ message: "User registered successfully", user, token });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

and the createUser function is handling the saving functionality of the user into the database. this api is working correctly in my postman, when i call the api like this:

http://localhost:3000/api/v3/users/signup

Now, for the client side code, i have created api.js file like this:

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:3000/api/v3/',
});

// api.defaults.headers.common['Authorization'] = 'Bearer your-token';

export default api;

and creeating a function like below to call that api

const createUser = async (username, email, password, firstName, lastName) => {

try {
    const response = api.post('users/signup', {
      username,
      email,
      password,
      firstName,
      lastName,
    });

console.log('ff', (await response).data);

const {token, user} = response.data;
auth.setToken(token);
return user;

} catch (error) {
    console.log('kk', error.message);
    throw error;
  }
};

bt on calling this function, i am getting the following results in terminal

kk Network Error
[AxiosError: Network Error]

i am not sure what is wrong here


Solution

  • i just had to change the baseURL from localhost to have the value of my ip address and it worked