16

I'm working on a project that has the frontend built in react and backend in spring and I can't seem to connect the two of them by using axios.

Keep in mind that the backend is working properly (also that I'm not very good at react).

this is the error I'm getting at the console:

  1. AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

    1. code: "ERR_NETWORK"

    2. config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}

    3. message: "Network Error"

    4. name: "AxiosError"

    5. request: XMLHttpRequest {data: undefined, onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, …}

    6. response: XMLHttpRequest {data: undefined, onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, …}

    7. [[Prototype]]: Error

this is my api.js:

import axios from 'axios';

const api = axios.create({
  baseURL: "https://localhost:8080"
});

export default api;

this is my App.js:

import './App.css';
import axios from "axios";
import {useEffect, useState} from 'react'
import api from './api.js';

function App() {
  const songs = async () => {
    try{
      const response = await api.get("/songs");
    }
    catch(err) {
      console.error(err);
    }
  };
  return (
     <div className="all-page">
             <main className="central-div">
                <h2>Taylor's Songs</h2>
                <button type="submit" className="quote-bttn" onClick={songs}>
                    FIND ME A QUOTE
                </button>
                <button type="submit" className="recommend-bttn">
                    GET ME A RECOMMENDATION
                </button>
             </main>
        </div>
  );
 
}

export default App;

the problem comes whenever I try to click the button "quote-bttn".

If anyone has any idea of how to fix this problem I'd really appreciate it!

(also, if there's anything I've left out, this is the full code: https://github.com/vitoriaacarvalho/my-taylor-swift-api/commit/0276222d35aa9a3fda8033f594d9727feded854b")

2
  • Sounds like cors error Commented Nov 19, 2022 at 18:20
  • @Konrad I had the same error and it was indeed a CORS error. But why axios swallows the CORS error like this (in Firefox at least) ? and there is nowhere to found any "CORS" error (console tab, network tab, ...) ? Commented Apr 9, 2023 at 18:15

7 Answers 7

9

You seem to be using an https request and not an http. Your base URL translates that your server is in your local machine. Local servers can be accessed using both http and https but if you are sure that you have configured your SSL certificate to access https requests then try checking your CORS policy/ restrictions on the backend. Ideally one will select CORS: "AllowAll" but you can also configure it so the request is only accepted from a designated client port.

Sign up to request clarification or add additional context in comments.

1 Comment

this helped me so much! thank you! for anyone in the future who has the same problem, here's how the code I used: public class WebMvcConfig implements WebMvcConfigurer{ Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("") .allowedOrigins("") .allowedHeaders("*") .allowCredentials(false) .maxAge(86400); } }
1
// Enable cors at the server side. 
const cors = require('cors')
const corsOption = {
    origin: ['http://localhost:3000'],
    credentials: true,
    methods: ["GET", "POST", "PUT", "DELETE"],
}
app.use(cors(corsOption));

Comments

1

I wrestled with this for hours/days. I had a React frontend at a domain (https://example.com) accessing data from a server on localhost (http://localhost:3001).

I gave my server a publicly accessible address (https://server.example.com)

https clients like to connect to https servers. Upgrade the server to an https and they can connect.

1 Comment

I am getting a similar error, I tried multiple ways to resolve this but still this error persists,
0

If you are trying on local, cors does not have importance. You need to make sure that you are pointing to the correct endpoint url on the backend.

For example if your endpoint url is http://localhost:5000/api in the backend and from the front you are pointing to http://localhost:5000/api2 this misspelling will couse 'Networ Error' from axios.

4 Comments

Cors do have importance in a local environment, since the port of the host matters in cors Same Origin Policy (w3.org/Security/wiki/Same_Origin_Policy)
Although you can test you connection without cors configuration that why I said it does not matter in local.
You can also POST something from postman using local without cors and it will work, so please remove "my answer is not useful".
No, you can not test a local or any another environment without cors, without disabling it in the first place. Also, cors functionality does not work in clients such as Postman, Insomnia, HTTPie or curl, simply because it is a protective measure that BROWSERS use when working with different domains (you can see the headers sent, but it is pretty much useless on the clients I mentioned). I will not be removing the "my answer is not useful" label by what I said above and because the question's answer does not correlate with cors, it is an issue with the op using https without setting up ssl
0

In my case I was getting error as [AxiosError: Network Error] because I was sending wrong key

export async function createUser(email, password) {
  console.log("createUser", email);
  console.log("createUser", password);
  await axios.post(
    "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=" + API_KEY,
    {
      emeil: email, <== this is the problem, key is "emeil" instead of "email"
      password: password,// for firebase your pasword should be more than 7 characters.
      returnSecureToken: true,
    }
  );

}

Comments

-1

When you are requesting localhost through Axios, add your network IP address instead of localhost, like this

https://192.168.0.122:8080

1 Comment

For me it still throws ERR_NETWORK even with https://192.168.31.34:3000/translate
-3

I don't know why exactly but problem in my case was I didn't render component inside test block but in describe.

---- wrong-----

describe("", ()=> {
render(<Component />); 
test("", () => {
})
})

---- correct -----

describe("", ()=> {
test("", () => {
render(<Component />);
})
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.