3 ways to solve cross-domain problems on the front end - Cross-domain problems occur when connecting to card readers

Background overview

When docking the card reader hardware during the development process, I interfaced with the C++ engineer. The C++ engineer wrote a program. After installing it on his computer, it will provide an interfacehttp://localhost:5001/api/XXXXX to obtain the read The data read by the card device (the data is processed by the C++ program)

Specific process:

  1. Install C++ program to local machine
  2. Place the magnetic card on the card reader (plug the card reader into your computer)
  3. Call interfacehttp://localhost:5001/api/XXXXX

Problems encountered in implementation

  • When we run the project locally, we can use [Method 1] reverse proxy;
  • When the project is deployed online, the reverse proxy we wrote on the front end will not be packaged into the package. The backendnginx needs to configure the proxy, but if the backend nginx proxy is used The address writtenhttp://localhost:5001 can only be proxied to the server, not to our local machine (the C++ program is installed on our own computer and cannot be accessed by the server)
  • If we directly request the address online http://localhost:5001/api/XXXXX , there will be cross-domain problems
  • [So] We need to solve the cross-domain problem: use [Method 2] [Method 3]

api.jsEncapsulated interface in file

export function XXX() {
    
    
  return request({
    
    
    url: '/RFID/api/XXX'
  })
}

调用接口A cross-domain problem occurred

GetCardNum() {
    
    
  GetCardNum().then((res) => {
    
    
    this.$set(this.formData, 'rfid', res.cardnum || '')
  })
}

solve

Method 1 - Reverse proxy

vue.config.jsIn the file, just proxy the address starting with /RFID to the local program address

module.exports = {
    
    
  // ...
  // webpack-dev-server 相关配置
  devServer: {
    
    
    host: '0.0.0.0',
    port: 8080,
    https: false,
    hotOnly: false,
    open: true, // 自动打开浏览器
    proxy: {
    
    
      // ...
      '^/RFID': {
    
    
        target: 'http://localhost:5001', // 【主要代码】
        pathRewrite: {
    
     '^/RFID': '' }
      },
      '/': {
    
    
        target: 'http://192.168.0.42:9000'
      }
    }
  },
  // 第三方插件配置
  pluginOptions: {
    
    
    // ...
  }
}

Method 2 - JSONP

It requires the cooperation of C++ engineers and calls the query parameter callback of the url.

Implementation 1

// 提供jsonp服务的url地址;
var url = 'http://localhost:5001/api/GetCardNum'
// 创建script标签,设置其属性;
var script = document.createElement('script')
script.setAttribute('src', url)
document.getElementsByTagName('head')[0].appendChild(script)
// 得到查询结果后的回调函数;
var callback = (data) => {
    
    
  var json = JSON.stringify(data)
  console.log('json----', json)
}
callback(132465)

Implementation 2 with the help of jQuery (what I use)

借助jQuery

import $ from 'jquery'


const that = this
$(function () {
    
    
  // 发起JSONP的请求
  $.ajax({
    
    
    url: 'http://localhost:5001/api/XXX',
    // 代表我们要发起JSONP的数据请求
    dataType: 'jsonp',
    jsonp: 'callback',
    jsonpCallback: 'fileCabinetHandler',
    success(res) {
    
    
      // res 数据即为接口返回的读取读卡器数据
    }
  })
})

Method 3 - Native Request

var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
    
    
  if (xhr.readyState === 4 && [200, '200'].includes(xhr.status)) {
    
    
    console.log('xhr.responseText----', xhr.responseText)
  }
}
xhr.open('get', 'http://localhost:5001/api/GetCardNum', true)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
xhr.send(null)

jsonpRequest('http://localhost:5001/api/GetCardNum', null)
  .then((response) => {
    
    
    console.log(response) // 处理返回的数据
  })
  .catch((error) => {
    
    
    console.error(error) // 处理错误信息
  })


var xhr = new XMLHttpRequest()
// xhr.open('get', 'http://192.168.10.106:5001/api/GetCardNum', true)
xhr.open('get', 'http://127.0.0.1:5001/api/GetCardNum2', true)
xhr.setRequestHeader('Content-Type', 'application/json') // 设置请求头中的 Content-Type
xhr.setRequestHeader('Access-Control-Allow-Origin', '*') // 添加允许跨域的请求头
xhr.onreadystatechange = function () {
    
    
  if (xhr.readyState === 4) {
    
    
    if (xhr.status === 200) {
    
    
      var data = JSON.parse(xhr.responseText)
      console.log('data----', data)
      // 处理响应数据
    } else {
    
    
      // 处理错误
    }
  }
}
xhr.send(
  JSON.stringify({
    
    
    // 请求体数据,如果不需要发送请求体,则可以省略该部分
    // 根据你的接口定义,替换成对应的请求体数据
  })
)

Method 4 - Request header to resolve cross-domain issues when making interface requests

// 接口请求头添加 Access-Control-Allow-Origin 为 * 解决跨域
if (config.url === '/RFID/api/GetCardNum') {
    
    
if (config.url === 'http://localhost:5001/api/GetCardNum') {
    
    
  config.url = 'http://localhost:5001/api/GetCardNum'
  // config.url = 'http://127.0.0.1:5001/api/GetCardNum'

  config.headers['Content-Type'] = 'application/json'
  config.headers['Access-Control-Allow-Origin'] = '*'

  console.log(
    'config.headers["Access-Control-Allow-Origin"]----',
    config.headers['Access-Control-Allow-Origin']
  )
}

Guess you like

Origin blog.csdn.net/m0_53562074/article/details/133177967