Hỏi đáp
Chia sẻ kiến thức, cùng nhau phát triển
Mình viết API bằng Nodejs Express nhưng khi dùng hàm Fetch của Javascript để gọi thì lỗi như sau
Access to fetch at 'http://localhost:3000/users' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: 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.
Đây là code Javascript khi gọi API của mình.
const api_url = "http://localhost:3000/users";
fetch(api_url)
.then((res) => res.json())
.then((data) => console.log(data));
Đây là Code API bên Nodejs
router.get('/', function(req, res, next) {
res.statusCode = 200
res.json( {
name: "Labor Day",
name_local: "",
language: "",
description: "",
country: "US",
location: "United States",
type: "National",
date: "09/07/2020",
date_year: "2020",
date_month: "09",
date_day: "07",
week_day: "Monday"
})
});
Mình gõ URL của API lên Web thì ok, có dữ liệu hết, chỉ có dùng JS để gọi API là gặp lỗi trên.
Thêm :
vào header web nó sẽ chấp nhận mọi web kết nối tới API.
Nếu muốn chỉ 1 số web nhất định có quyền kết nối API thì thay đổi 1 tí
Access-Control-Allow-Origin: abc.com