Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error when accessing NodeJS express api in Docker container

I have NodeJS api and NextJS application in Separate docker containers when I'm in host machine its working fine, but when I'm running inside docker containers its giving CORS error.

My express config in API

app.use(cors({
    credentials: true,
    origin: 'http://localhost:3000/' // Allowing front-end running port 3000
}));

app.use(cookieParser());
app.use(bodyParser.json());
app.use(urlencoded({ extended: true }));
app.use(json());
app.enable("trust proxy");
app.use(methodOverride());

In front-end APP NextJS axios config

const axiosInstance = axios.create({ baseURL: 'http://localhost:4000/', withCredentials: true });

enter image description here

enter image description here

Its woking fine when im running API from host machine, with same configuration its giving CORS error in Docker.

like image 281
Wimal Weerawansa Avatar asked May 08 '26 12:05

Wimal Weerawansa


1 Answers

As i can see your API configuration seems correct, but in your NextJS create pages/api/whatever.js and call your API from handler

import axios from 'axios';
axios.defaults.withCredentials = true;

export default async function handler(req, res){
   try {
     const response = axios.post('http://localhost:4000/<your_login_api_URL>', req.body)
   }catch(error) {
     // handle error here
   }

}

this will work and its safer way to mask your back end API calls from front end.

like image 63
Kamaal ABOOTHALIB Avatar answered May 11 '26 02:05

Kamaal ABOOTHALIB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!