Initial Problem
I work on a web application (react) that accesses data via an API. The API runs for development reasons on a docker container on my local machine. Simple GET requests (via axios) got me CORS complications (...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
).
A bit of researching solved my problem by running a nginx reverse proxy in another container. I basically used this configuration for the nginx server.
New Problem
As I progress in building my application, I come to a point where I need to send the JWT to the API to access and alter some entries. Requests that need sending a JWT again get me CORS error messages.
The API checks the JWT signature (RS256 generated). I just have to forward it to the API server.
ALSO: simple curl requests with the JWT from the console are working.
Configuration
- axios
const axiosConfig = {
responseType: "json",
withCredentials: false,
mode: "no-cors",
headers: {
'Access-Control-Allow-Origin': "*",
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
'Content-Type': 'application/json',
'Authorization': 'Bearer <JWT as string>',
},
};
const apiGetRequest = async (route, callback) => {
try {
const apiUrl = URL route;
axios.get(apiUrl, {
axiosConfig
})
.then(res => {
callback(res);
})
.catch(function (error) {
console.log(error);
});
} catch (error) {
console.log(error);
}
}
Docker Image for api
version: "3.9"
services:
db:
image: mariadb:latest
container_name: db
env_file:
- ./mariadb/.env
volumes:
- ./mariadb/create-schema-docker.sh /docker-entrypoint-initdb.d
- db-data:/var/lib/mysql
ports:
- 3306:3306
rest:
image: mds4ul/station-registry:latest
container_name: api
environment:
- DB_HOST=db
- CONTEXT_PATH=api
env_file:
- ./rest/.env
depends_on:
- db
ports:
- 80:8080
volumes:
db-data:
Questions
- Why do I get CORS errors for requests where a jwt is needed and not for requests that do not require one?
- Which part do I have to change to make this work?
CodePudding user response:
So answer another question to an embarrassing easy problem of mine.
I switched to an express.js proxy server with the following configuration:
const express = require('express')
const app = express()
const axios = require('axios')
const cors = require('cors')
var bodyParser = require('body-parser')
app.use(cors({
origin: '*'
}))
app.use(bodyParser.json())
require('dotenv').config()
const headers = {
"X-Authorization": <token>,
}
app.get(':endpoint([\\/\\w\\.-]*)', function (req, res) {
const endpoint = (process.env.API_BASE_URL).replace(/\/$/, "") req.params.endpoint;
axios.get(endpoint, { headers }).then(response => {
res.json(response.data)
}).catch(error => {
res.json(error)
})
})
app.listen(3001)
I assume I just could not figure out my nginx configuration for this use case. So with express.js I can access now resources which need authorization.