HTML5 – CORS
隨著網絡應用程序的不斷發展,跨域資源共享(CORS)成為一種必不可少的技術。愛掏網 - it200.com本文將講解CORS及其在HTML5中的應用。愛掏網 - it200.com
在傳統的web應用中,瀏覽器限制了不同域之間的網絡通信(安全限制)。愛掏網 - it200.com在此情況下,如果你在一個域中有網頁,而該網頁需要從另一個域獲取數據,那么瀏覽器會拒絕請求。愛掏網 - it200.com這種情況就稱為“跨域請求”。愛掏網 - it200.com
為了解決這種情況,CORS誕生了。愛掏網 - it200.comCORS是一種Web標準,允許瀏覽器向跨域服務器請求資源,并讓服務器端允許特定域名的請求。愛掏網 - it200.com
CORS的應用
假設你有一個web應用,你需要從另一個域獲取資源不受限制。愛掏網 - it200.com例如,你在http://example.com
網站上有一個JavaScript文件,希望從另一個域http://api.example.com
獲取一些數據。愛掏網 - it200.com可以使用CORS配置來實現。愛掏網 - it200.com具體方法如下:
在服務端(http://api.example.com
)中,設置響應頭,允許特定域名的訪問。愛掏網 - it200.com一般使用如下PHP代碼實現:
header("Access-Control-Allow-Origin: http://example.com");
通常,響應頭包括以下參數:
- Access-Control-Allow-Origin:該域名被允許訪問該服務器。愛掏網 - it200.com
- Access-Control-Allow-Methods:該服務器允許的HTTP方法類型。愛掏網 - it200.com
- Access-Control-Max-Age:預處理請求的時間(以秒為單位)。愛掏網 - it200.com
- Access-Control-Allow-Headers:允許客戶端傳遞的請求頭。愛掏網 - it200.com
在客戶端(http://example.com
)中,使用XMLHttpRequest對象發送跨域請求。愛掏網 - it200.com代碼如下:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.example.com/data', true);
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
上述代碼中,withCredentials屬性指示客戶端在CORS請求中發送憑證,如:cookie、HTTP認證或OAuth token。愛掏網 - it200.com如果要發送跨域cookies,則在服務端(http://api.example.com
)響應頭中添加Access-Control-Allow-Credentials: true
。愛掏網 - it200.com
一個完整的CORS例子
為了更好地理解CORS的應用,請看下面的例子。愛掏網 - it200.com該例子基于Spring框架,其中http://localhost:8080
為web應用,http://localhost:8081
為RESTful服務。愛掏網 - it200.com
服務端代碼:
@RestController
@CrossOrigin(origins = "http://localhost:8080")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getUsers() {
return userService.getUsers();
}
@PostMapping("/users")
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder builder) {
userService.createUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/users/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
}
上述代碼使用了Spring框架的@CrossOrigin
注解,指出了web應用http://localhost:8080
可以跨域訪問RESTful服務。愛掏網 - it200.com同時,也包含一個獲取用戶列表和添加用戶的控制器。愛掏網 - it200.com
客戶端代碼:
const getUsersBtn = document.querySelector('#get-users-btn');
const usersTable = document.querySelector('#users-table');
const nameInput = document.querySelector('#name');
const emailInput = document.querySelector('#email');
const createUserBtn = document.querySelector('#create-user-btn');
getUsersBtn.addEventListener('click', getUsers);
createUserBtn.addEventListener('click', createUser);
function getUsers() {
fetch('http://localhost:8081/users')
.then(response => response.json())
.then(data => {
let tableHtml = '<tr><th>ID</th><th>Name</th><th>Email</th></tr>';
for (let user of data) {
tableHtml += `<tr><td>{user.id}</td><td>{user.name}</td><td>${user.email}</td></tr>`;
}
usersTable.innerHTML = tableHtml;
})
.catch(error => {
console.error('Error:', error);
});
}
function createUser() {
const user = {
name: nameInput.value,
email: emailInput.value
};
fetch('http://localhost:8081/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
if (response.status === 201) {
alert('User created successfully');
} else {
alert('Failed to create user');
}
})
.catch(error => {
console.error('Error:', error);
});
}
上述代碼中,使用了fetch()
方法發送了兩個不同的請求:
- 獲取用戶信息:發送GET請求到
http://localhost:8081/users
。愛掏網 - it200.com - 創建用戶:發送POST請求到
http://localhost:8081/users
,并在請求體中包含用戶數據。愛掏網 - it200.com
結論
CORS是一種web標準,允許瀏覽器跨域請求資源。愛掏網 - it200.com服務端通過配置響應頭,允許特定域名的跨域請求。愛掏網 - it200.com客戶端通過XMLHttpRequest對象或fetch()方法發送跨域請求。愛掏網 - it200.com在HTML5中,CORS的應用非常廣泛,對于一些需要從外部域獲取資源的web應用,是一種必不可少的技術。愛掏網 - it200.com