1. 程式人生 > >4、CORS跨域請求限制與解決(預請求)

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')