htmlhtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>cors例子</title> </head> <body> <script> var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼 xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 瀏覽器執行代碼 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { console.log(xmlhttp) } } xmlhttp.open("GET","http://localhost:3000/get",true); xmlhttp.send(); </script> </body> </html>
咱們建立一個ajax 請求接口 端口爲3000git
後端的端口爲4000web
server.jsajax
const express = require('express'); const app = express(); app.get('/get',function(req,res) { res.end('跨域處理') }) app.listen(3000, () => console.log('The server is starting at port 3000'));
產生跨域:express
添加跨域處理:json
app.all('*', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); //Access-Control-Allow-Headers ,可根據瀏覽器的F12查看,把對應的粘貼在這裏就行 res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Methods', '*'); res.header('Content-Type', 'application/json;charset=utf-8'); next(); });
效果:後端
輸出;跨域處理跨域