Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http服务下,请求接口会报跨域,能不能麻烦给个解决跨域的示例,谢谢 #52

Closed
zhuibo66 opened this issue Nov 7, 2023 · 7 comments

Comments

@zhuibo66
Copy link

zhuibo66 commented Nov 7, 2023

http服务下,请求接口会报跨域,能不能麻烦给个解决跨域的示例,谢谢

@hiroi-sora
Copy link
Owner

hiroi-sora commented Nov 7, 2023

请尝试下述操作:

  1. 打开 UmiOCR-data\py_src\server\web_server.py
  2. 第13行,原本是:
from .bottle import Bottle, ServerAdapter, request, HTTPResponse

现在改为:

from .bottle import Bottle, ServerAdapter, request, HTTPResponse, response
  1. 第21行,插入一个函数:
# 设置响应头,允许跨域
@UmiWeb.hook("after_request")
def enable_cors():
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Headers"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
  1. 测试跨域请求。

hiroi-sora added a commit that referenced this issue Nov 7, 2023
@zhuibo66
Copy link
Author

zhuibo66 commented Nov 7, 2023

请尝试下述操作:

  1. 打开 UmiOCR-data\py_src\server\web_server.py
  2. 第13行,原本是:
from .bottle import Bottle, ServerAdapter, request, HTTPResponse

现在改为:

from .bottle import Bottle, ServerAdapter, request, HTTPResponse, response
  1. 第21行,插入一个函数:
# 设置响应头,允许跨域
@UmiWeb.hook("after_request")
def enable_cors():
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Headers"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
  1. 测试跨域请求。

试了下,如果直接用案例中的js代码,会报:Access to fetch at 'http://127.0.0.1:1224/api/ocr' from origin 'null' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

const url = 'http://127.0.0.1:1224/api/ocr';
const data = {
    base64: 'iVBORw0KGgoAAAANSUhEUgAAAC4AAAAXCAIAAAD7ruoFAAAACXBIWXMAABnWAAAZ1gEY0crtAAAAEXRFWHRTb2Z0d2FyZQBTbmlwYXN0ZV0Xzt0AAAHjSURBVEiJ7ZYrcsMwEEBXnR7FLuj0BPIJHJOi0DAZ2qSsMCxEgjYrDQqJdALrBJ2ASndRgeNI8ledutOCLrLl1e7T/mRkjIG/IXe/DWBldRTNEoQSpgNURe5puiiaJehrMuJSXSTgbaby0A1WzLrCCQCmyn0FwoN0V06QONWAt1nUxfnjHYA8p65GjhDKxcjedVH6JOejBPwYh21eE0Wzfe0tqIsEkGXcVcpoMH4CRZ+P0lsQp/pWJ4ripf1XFDFe8GHSHlYcSo9Es31t60RdFlN1RUmrma5oTzTVB8ZUaeeYEC9GmL6kNkDw9BANAQYo3xTNdqUkvHq+rYhDKW0Bj3RSEIpmyWyBaZaMTCrCK+tJ5Jsa07fs3E7esE66HzralRLgJKp0/BD6fJRSxvmDsb6joqkcFXGqMVVFFEHDL2gTxwCAaTabnkFUWhDCHTd9iYrGcAL1ZnqIp5Vpiqh7bCfua7FA4qN0INMcN1+cgCzj+UFxtbmvwdZvGIrI41JiqhZBWhhF8WxorkYPpQwJiWYJeA3rXE4hzcwJ+B96F9zCFHC0FcVegghvFul7oeEE8PvHeJqC0w0AUbbFIT8JnEwGbPKcS2OxU3HMTqD0r4wgEIuiKJ7i4MS16+og8/+bPZRPLa+6Ld2DSzcAAAAASUVORK5CYII=',
    // Paddle引擎插件格式
    options: {
        cls: false,
        language: "models/config_chinese.txt",
        limit_side_len: 960
    }
    // Rapid引擎插件格式
    // options: {
    //     angle: false,
    //     language: "简体中文(V4)",
    //     maxSideLen: 1024
    // }
};

fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
 
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });

@hiroi-sora
Copy link
Owner

你是在什么框架下运行js的呢?试一下浏览器环境有没有问题?

image

@hiroi-sora
Copy link
Owner

hiroi-sora commented Nov 7, 2023

另外,作为一种临时措施,前端层面可以往fetch的字典中添加 mode: 'no-cors' 来绕过跨域问题:

fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
        mode: 'no-cors', // 添加这一行
    })

@zhuibo66
Copy link
Author

zhuibo66 commented Nov 8, 2023

我目前用的版本:Umi-OCR_Paddle_dev_20231105

说下我这边的复现步骤:

1、本地创建test.html文件,内容如下,然后直接用浏览器打开,F12打开控制台提示报错Access to fetch at 'http://127.0.0.1:1224/api/ocr' from origin 'null' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
</head>

<body>
    <script>
        const url = 'http://127.0.0.1:1224/api/ocr';
        const data = {
            base64: 'iVBORw0KGgoAAAANSUhEUgAAAC4AAAAXCAIAAAD7ruoFAAAACXBIWXMAABnWAAAZ1gEY0crtAAAAEXRFWHRTb2Z0d2FyZQBTbmlwYXN0ZV0Xzt0AAAHjSURBVEiJ7ZYrcsMwEEBXnR7FLuj0BPIJHJOi0DAZ2qSsMCxEgjYrDQqJdALrBJ2ASndRgeNI8ledutOCLrLl1e7T/mRkjIG/IXe/DWBldRTNEoQSpgNURe5puiiaJehrMuJSXSTgbaby0A1WzLrCCQCmyn0FwoN0V06QONWAt1nUxfnjHYA8p65GjhDKxcjedVH6JOejBPwYh21eE0Wzfe0tqIsEkGXcVcpoMH4CRZ+P0lsQp/pWJ4ripf1XFDFe8GHSHlYcSo9Es31t60RdFlN1RUmrma5oTzTVB8ZUaeeYEC9GmL6kNkDw9BANAQYo3xTNdqUkvHq+rYhDKW0Bj3RSEIpmyWyBaZaMTCrCK+tJ5Jsa07fs3E7esE66HzralRLgJKp0/BD6fJRSxvmDsb6joqkcFXGqMVVFFEHDL2gTxwCAaTabnkFUWhDCHTd9iYrGcAL1ZnqIp5Vpiqh7bCfua7FA4qN0INMcN1+cgCzj+UFxtbmvwdZvGIrI41JiqhZBWhhF8WxorkYPpQwJiWYJeA3rXE4hzcwJ+B96F9zCFHC0FcVegghvFul7oeEE8PvHeJqC0w0AUbbFIT8JnEwGbPKcS2OxU3HMTqD0r4wgEIuiKJ7i4MS16+og8/+bPZRPLa+6Ld2DSzcAAAAASUVORK5CYII=',
            // Paddle引擎插件格式
            options: {
                cls: false,
                language: "models/config_chinese.txt",
                limit_side_len: 960
            }
            // Rapid引擎插件格式
            // options: {
            //     angle: false,
            //     language: "简体中文(V4)",
            //     maxSideLen: 1024
            // }
        };

        fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data),

            })
            .then(response => response.json())
            .then(data => {
                console.log(data);
            })
            .catch(error => {
                console.error(error);
            });
    </script>
</body>

</html>

2、在1的基础上在fetch中增加中添加mode: 'no-cors' ,然后直接用浏览器打开,F12打开控制台提示报错,POST http://127.0.0.1:1224/api/ocr 500 (Internal Server Error)

hiroi-sora added a commit that referenced this issue Nov 8, 2023
@hiroi-sora
Copy link
Owner

hiroi-sora commented Nov 8, 2023

OK,感谢复现步骤。已补充修复,请参照 此commit 修改python代码。(js代码无需使用mode: 'no-cors'

测试:

更新前,按你的复现步骤:
image

更新后可恢复正常:
image

@zhuibo66
Copy link
Author

zhuibo66 commented Nov 8, 2023

OK,感谢复现步骤。已补充修复,请参照 此commit 修改python代码。(js代码无需使用mode: 'no-cors'

测试:

更新前,按你的复现步骤: image

更新后可恢复正常: image

太给力了,给你点个赞,已经可以了哈。

@zhuibo66 zhuibo66 closed this as completed Nov 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants