I have a Vue Frontend inside a docker container which connects to a Spring-boot backend in another container. The backend gets its data from a MongoDB (also in a container). When I build my Vue frontend into a docker container, and try to get data from the Database, I get a CORS error.
Access to XMLHttpRequest at 'http://localhost:8010/persons' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My backend is running in a docker container with port 8010 published and my Vue frontend in a container with port 8080. Allow-cross-origin is already set in my backend.
this is the dockerfile in my frontend:
FROM node:lts-alpine
RUN npm install -g http-server
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . /app
RUN npm run build
EXPOSE 8080
CMD ["http-server", "dist"]
and build the image with:
docker build -t frontend .
and
docker run -d -it -p 8080:8080 --name frontend frontend
So in Vue i set axios to:
axios.defaults.baseURL = "http://localhost:8010/";
axios.defaults.headers.get["Content-Type"] = "application/json";
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.get["Access-Control-Allow-Origin"] = "*";
and make this request:
axios.get("/persons").then(res => {
if (res.data.length === 0) {
console.log("No Persons found!", res.data);
}
console.info("ready", res.data);
for (let i in res.data) {
this.persons.push(res.data[i]);
}
});
In my Spring-boot backend i already allow cross-origin access.
And in development mode everything works, because I can proxy the request inside the vue.config.js file with
devServer: {
proxy: "http://localhost:8010"
}
and i my browser i also can connect to my backend and to swagger. Just the vue app doesn't find the backend. What is the problem there? How can i avoid the cors error and reach my backend?
sorry for my bad english