thắc mắc Lỗi cors khi call api spring từ react

Yêu Linh Nhất

Senior Member
E có call 1 api từ react như này:
1697078162158.png


Nhưng bị lỗi: Access to fetch at 'http://localhost:8762/account/api/test/user' from origin 'http://localhost:3000' 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.

E tra gg cách duy nhất e làm đc là bật chrome ở chế độ --disable-web-security thì bình thường, nhưng cách này ko ổn.
Bên gateway và account e đã config cors :
1697078372689.png


1697078396560.png


Các bác có cao kiến cứu e ca này :v
 
cái này tôi hay fix = cách cho nginx làm proxy rồi set Origin là $http_origin luôn, bác tham khảo thử
NGINX:
proxy_hide_header 'Access-Control-Allow-Origin'; 
proxy_hide_header 'Access-Control-Allow-Credentials';
if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' $http_origin always;
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,authorization,Authorization,access-control-allow-origin,accept-version';
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 204;
}
if ($request_method = 'POST') {
    add_header 'Access-Control-Allow-Origin' $http_origin always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,authorization,Authorization,access-control-allow-origin,accept-version';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' $http_origin always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,authorization,Authorization,access-control-allow-origin,accept-version'; 
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}

if ($request_method = 'PUT') {
    add_header 'Access-Control-Allow-Origin' $http_origin always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,authorization,Authorization,access-control-allow-origin,accept-version';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}

if ($request_method = 'DELETE') {
    add_header 'Access-Control-Allow-Origin' $http_origin always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,authorization,Authorization,access-control-allow-origin,accept-version';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
Trong cụm server include đoạn trên vào là đc
NGINX:
server {
    server_name voz.test;

    location / {
        include common-conf/cors.conf;
        include common-conf/upgradews.conf;

        proxy_pass http://192.168.10.177:80;
    }

    error_log off;
    access_log off;

    listen 80;
}
đoạn config header kia bị deplicate code nhưng mình lười sửa bác sửa lại cho đẹp nhé
wEqlboB.png
 
bác thử để thêm credentials ở cái fetch nữa xem, sau cái header thêm credentials: 'include' , nếu axios thì withCredentials : true
 
Em gà mờ thường dùng dạng vầy thớt ạ :beat_brick: em để trước layer controller hoặc cả SpringBootApplication luôn
Java:
@CrossOrigin(origins = "*", allowedHeaders = "*")
 
Tôi làm thì dựng thêm 1 con API gateway cho ngầu

Thớt đang học thì tìm hiểu thêm Kong API gateway

Đáng công sức đấy
 
Em gà mờ thường dùng dạng vầy thớt ạ :beat_brick: em để trước layer controller hoặc cả SpringBootApplication luôn
Java:
@CrossOrigin(origins = "*", allowedHeaders = "*")
thường thế này là allow cors rồi :big_smile: k biết cách nào hơn nữa :too_sad:
 
Bên gateway, bạn config này thử, không chắc lắm nha:

application.yml
Code:
spring:
  ...
  cloud:
    gateway:
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
      globalcors:
        add-to-simple-url-handler-mapping: true
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods: "*"
 
Bỏ cái suy nghĩ là allow * đi bác :D Đọc thêm cors để biết công dụng của nó nhé! Phải config ở server để pass được cors của local ( trên dev, staging thôi ) hoặc run chrome ở chế độ without cors nhé.
Bác tham khảo cách run chrome without cors nhé
 
Last edited:
Cái này em hay dùng extension để pass cho tiện.
Hoặc bản chrome mới gần đây đã cho sửa header nhưng có vẻ hơi mất công mỗi lần call api.
1697124843552.png
 
ở python thì mình thêm dòng này là dc CORS(app, resources={r"/api/": {"origins": ""}})
còn js thì ko rõ cho lắm , nhưng đại loại là tìm cách cho phép truy cập từ tất cả
cái này phải set ở server api
 
Trước em có chèn thêm đoạn này dzo là nó hết lỗi, rồi deploy lên prod nó lại lúc lỗi lúc không :)))
@app.after_request # blueprint can also be app~~
def after_request(response):
response.headers.add('Access-Control-Allow-Origin','*')
response.headers.add('Access-Control-Allow-Methods','*')
response.headers.add('Access-Control-Allow-Credentials','true')
response.headers.add('Access-Control-Allow-Headers','*')
return response
 
Back
Top