【发布时间】:2021-06-26 14:13:55
【问题描述】:
我正在尝试使用 ReactJS 从 orthanc 服务器加载图像。由于 orthanc 不支持 CORS,我使用 nginx 设置了代理服务器。 Nginx 和 orthanc 在 docker 容器中,nginx 可以通过 http://orthanc:8042 与 orthanc 对话。 按照我的 nginx 配置文件:
events {
worker_connections 1024;
}
http {
server {
listen 80 default;
server_name 127.0.0.1 localhost;
location /orthanc/ {
proxy_pass http://orthanc:8042;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite /orthanc(.*) $1 break;
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
}
}
}
如果我尝试使用邮递员的请求,来自 nginx 的 CORS 标头似乎可以工作:
但如果我尝试通过 ReactJS / axios 调用 api,我会被 CORS 策略阻止:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8085/orthanc/instances/5cd65944-8a37c5f3-ecd23660-3238d171-41728b44/preview. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8085/orthanc/instances/5cd65944-8a37c5f3-ecd23660-3238d171-41728b44/preview. (Reason: CORS request did not succeed).
这是我的要求:
import axios from 'axios'
export const PacsService = {
find,
authToken,
}
function find() {
authToken()
var response = instance.get('http://localhost:8085/orthanc/instances/5cd65944-8a37c5f3-ecd23660-3238d171-41728b44/preview')
console.log(response.data)
}
// -- Axios https://github.com/axios/axios#config-defaults
const instance = axios.create({
//baseURL: `${config.ORTHANC_BASE_URL}`,
headers: {
'Content-Type': 'application/json'
}
})
instance.interceptors.request.use(request => {
console.log('Starting Request', JSON.stringify(request, null, 2))
return request
})
instance.interceptors.response.use(response => {
console.log('Response:', JSON.stringify(response, null, 2))
console.log(response)
return response
})
// -- Helper functions
export function authToken() {
// set default header to be sent with every request
instance.defaults.headers.common.Authorization = `Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXX`
}
【问题讨论】:
标签: reactjs api nginx axios cors