续跨域解决方案(1)https://blog.csdn.net/Genius_cxx/article/details/102571958讲解了跨域的几种情况和出现的缘由。
本期讲解node中跨域的两种解决方式
我们经常遇到这种情况,后端给我们提供了接口,但是由于一些安全性的考虑,不愿意配置跨域信息。这个时候,我们就要自己搭建 node 服务器来转发请求以实现跨域
- 环境安装
npm init -y
npm i request standard pm2 nodemon --save
- 配置 node script
// package.json
{
"name": "nodeProxy",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "pm2 start index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"request": "^2.85.0"
},
"devDependencies": {
"nodemon": "^1.17.2",
"standard": "^11.0.1"
}
}
- 配置 index.js
var http = require('http')
var request = require('request')
var server = http.createServer(onRequest).listen(3000)
function onRequest (req, res) {
//配置跨域 http://localhost:8080可写成 *
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080')
//配置跨域请求方式
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
res.setHeader('Access-Control-Allow-Credentials', true)
req.url = 'http://frelimitbeta.jd.com/service' + req.url
console.log(`SUCCESS CONNECT ${req.url}`)
if (req.method === 'GET') {
if (req.url) {
// request方法返回的对象兼具可读和可写权限,所以可以直接通过pipe给客户端返回值
request({
url: req.url
}).on('error', function (e) {
res.end(e)
}).pipe(res)
} else {
res.end('no url found')
}
} else if (req.method === 'POST') {
if (req.url) {
let body = ""
req.on('data', function (chunk) {
body += chunk;
})
req.on('end', function () {
// 这里的 from 其实就是把 data 组装成自己想要的格式
let data = body.split('=')
request.post(req.url).form({body:data[1]}).on('error', e => res.end(e)).pipe(res)
})
} else {
res.end('wrong post')
}
} else {
res.end('wrong method')
}
}