| 
                            
                                  Nodejs解决跨域(CORS)前后端分离的大环境下,受制于同源策略,我们需要懂得实现CORS(Cross-Origin Resource Sharing) 手动配置在nodejs中,req 和 res 参数在中间件间都指向同一对象,这样我们就可以在头中间件中修改res 的header。如下: 
	
		
			| 1 2 3 4 5 6 7 8 | const express = require('express')    const app = express();    app.use((req, res) => {     //在这里手动配置     res.header('Access-Control-Allow-Origin', 'example.com'); }) |  CORS模块我们也可以通过引入cors模块快速配置。 
	
		
			| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | npm i cors --save   //不是node的内置模块,需要先下载   const express = require('express') const cors = require('cors')    const app = express();    const corsConfig = {   origin:'http://localhost:8080',   credentials:true, } //使用默认 app.use(cors()) //或修改默认配置 app.use(cors(corsConfig))  |  axios值得注意的一点是cors模块会将 Access-Control-Allow-Origin 默认配为 *,但是axios不接受通配符*。而且axios还需要 Access-Control-Allow-Credentials 属性为true。 Credentials我们可以手动配置,Access-Control-Allow-Origin 我们可以如下配置 : 
	
		
			| 1 2 3 4 5 6 7 8 9 10 11 12 13 | const express = require('express') const cors = require('cors')    const app = express();    //使用默认 app.use(cors())    .use((req, res, next) => {         console.log(req);         res.setHeader('Access-Control-Allow-Origin',req.origin),         next()     }) //req.origin是网关地址 如:http://192.168.1.1  |  注意:本地调试的时候axios不认为 localhost:8080 等于127.0.0.1:8080 Nodejs CORS跨域问题在响应头里设置:'Access-Control-Allow-Origin': '*' index.html 
	
		
			| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE html> <html lang="en">   <head>     <meta charset="UTF-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>cors</title> </head>   <body>     <script>         // 请求地址         fetch('http://localhost:3000/api/data')             // 请求体解析             .then(res => res.json())             // 获得数据             .then(result => console.log(result))     </script> </body>   </html> |  server.js 
	
		
			| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | const http = require('http'); const libUrl = require('url')   http.createServer((req, res) => {     const url = libUrl.parse(req.url, true);       if (url.pathname === '/favicon.ico') return;       if (url.pathname === '/api/data') {         res.writeHead(200, {             'Content-Type': 'Application/json',             // 设置允许所有端口访问             'Access-Control-Allow-Origin': '*'         });         let obj = {             name: '张三',             age: 20,             sex: '男'         };         res.write(JSON.stringify(obj));     }     res.end(); }).listen(3000) |  
 |