跨域 (2) cors
html
<!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 请求接口 端口为3000
后端的端口为4000
server.js
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'));
产生跨域:
添加跨域处理:
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(); });
效果:
输出;跨域处理
越努力越幸运