Skip to content

Commit fdbb60e

Browse files
bugfix: 修复跨域问题。
1 parent 0b85499 commit fdbb60e

4 files changed

Lines changed: 18 additions & 5 deletions

File tree

packages/mitmproxy/src/lib/interceptor/impl/req/OPTIONS.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ module.exports = {
1919
const { rOptions, log } = context
2020

2121
// 不是 OPTIONS 请求,或请求头中不含 origin 时,跳过当前拦截器
22-
if (rOptions.method !== 'OPTIONS' || rOptions.headers.origin == null) {
22+
if (rOptions.method !== 'OPTIONS' || !rOptions.headers.origin) {
2323
return
2424
}
2525

packages/mitmproxy/src/lib/interceptor/impl/req/baiduOcr.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,11 @@ module.exports = {
118118

119119
const headers = {
120120
'Content-Type': 'application/json; charset=utf-8',
121-
'Access-Control-Allow-Origin': '*',
121+
}
122+
123+
if (rOptions.headers.origin) {
124+
headers['Access-Control-Allow-Credentials'] = 'true'
125+
headers['Access-Control-Allow-Origin'] = rOptions.headers.origin
122126
}
123127

124128
// 获取配置(api 由 getConfig 以局部变量形式返回,不写入共享配置对象,并发安全)

packages/mitmproxy/src/lib/interceptor/impl/res/AfterOPTIONSHeaders.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@ module.exports = {
77
responseIntercept (context, interceptOpt, req, res, proxyReq, proxyRes, ssl, next) {
88
const { rOptions, log } = context
99

10-
if (rOptions.method === 'OPTIONS') {
10+
if (rOptions.method === 'OPTIONS' || !rOptions.headers.origin) {
1111
return
1212
}
1313

1414
const headers = {
1515
'Access-Control-Allow-Credentials': 'true',
16-
'Access-Control-Allow-Origin': '*',
16+
'Access-Control-Allow-Origin': rOptions.headers.origin,
1717
'Cross-Origin-Resource-Policy': interceptOpt.optionsCrossPolicy || 'cross-origin',
1818
}
1919

packages/mitmproxy/src/lib/proxy/mitmproxy/createRequestHandler.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,16 @@ module.exports = function createRequestHandler (createIntercepts, middlewares, e
334334
if (!res.writableEnded) {
335335
try {
336336
const status = e.status || 500
337-
res.writeHead(status, { 'Content-Type': 'text/html;charset=UTF8' })
337+
338+
const headers = { 'Content-Type': 'text/html;charset=UTF8' }
339+
340+
// headers.Access-Control-Allow-*:避免跨域问题
341+
if (rOptions.headers.origin) {
342+
headers['Access-Control-Allow-Credentials'] = 'true'
343+
headers['Access-Control-Allow-Origin'] = rOptions.headers.origin
344+
}
345+
346+
res.writeHead(status, headers)
338347
res.write(`<style>
339348
p {
340349
margin: 10px 0;

0 commit comments

Comments
 (0)