React + fetch API + Docker – net::ERR_NAME_NOT_RESOLVED on specific page

  docker, next.js, reactjs

I am using Next.js for the React code and Docker.
I am using the Docker service name and port to fetch data using the fetch API and it’s working on some pages where I use GET. But now I try to POST and I get POST http://nginx:8080/api/register net::ERR_NAME_NOT_RESOLVED.

This is the working ListItems.jsx page where I’m using fetch:

function Items({ data }) {
  return (
    <div>
        {console.log(data)} // this works
    </div>
  )

}
    
export async function getServerSideProps() {
  const res = await fetch('http://nginx:8080/api/items', {
    method: 'GET',
  })  
  const { data } = await res.json()
  return { props: { data } };
}

export default Items

And this is the Register.jsx page where I get net::ERR_NAME_NOT_RESOLVED:

export default function Register() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

const handleSubmit = (evt) => {
    evt.preventDefault();
    async function postData(url = '', data = {}) {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
        });
        return response.json();
    }
    postData('http://nginx:8080/api/register', { email: email, password: password })
        .then(data => {
            console.log(data);
        })
        .catch(error => {
            console.error('There has been a problem with your fetch operation:', data);
        })
}


    return (
        <div>
            // form template here
        </div>
    )
}

Source: Docker Questions

LEAVE A COMMENT