4、CORS跨域请求限制与解决(预请求)

test.html

<script>
    fetch('http://localhost:8887/', {
      method: 'PUT',
      headers: {
        'X-Test-Cors': '123'
      }
    })
</script>

server.js

const http = require('http')

http.createServer((request, response) => {
  console.log('request come', request.url)

  // 多个Access-Control-Allow-Origin只需通过request的host动态判断
  response.writeHead(200, {
    'Access-Control-Allow-Origin': '*', // 这里可以限制相关ip
    'Access-Control-Allow-Headers': 'X-Test-Cors', // 允许的请求头
    'Access-Control-Allow-Methods': 'POST, PUT, Delete', // 默认允许GET、HEAD、POST
    'Access-Control-Max-Age': '1000'  // 1000s之内不需要发送预请求验证
  })
  response.end('123')

}).listen(8887)

console.log('server listening on 8887')

猜你喜欢

转载自www.cnblogs.com/zouxinping/p/10124417.html
今日推荐