跨域解决方案(2)

续跨域解决方案(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')
  }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值