最初的問題
我在一個通過 API 訪問資料的 Web 應用程式 (react) 上作業。該 API 出于開發原因在我的本地機器上的 docker 容器上運行。簡單的 GET 請求(通過 axios)讓我遇到了 CORS 問題(...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.)。
一些研究通過在另一個容器中運行 nginx 反向代理解決了我的問題。我基本上將這個配置用于 nginx 服務器。
新問題
在構建應用程式的程序中,我需要將 JWT 發送到 API 以訪問和更改一些條目。需要再次發送 JWT 的請求會收到 CORS 錯誤訊息。
API 檢查 JWT 簽名(生成的 RS256)。我只需要將它轉發到 API 服務器。
另外:來自控制臺的 JWT 的簡單 curl 請求正在作業。
配置
- 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);
}
}
nginx配置
用于 API 的 Docker 映像
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:
問題
- 為什么對于需要 jwt 的請求而不是不需要 jwt 的請求會出現 CORS 錯誤?
- 我必須更改哪個部分才能完成這項作業?
uj5u.com熱心網友回復:
所以回答我一個令人尷尬的簡單問題的另一個問題。
我切換到具有以下配置的 express.js 代理服務器:
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)
我想我只是無法弄清楚這個用例的 nginx 配置。因此,使用 express.js,我現在可以訪問需要授權的資源。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480564.html
