server1.js
const http = require('http'); const fs = require('fs'); http.createServer(function(req, res) { console.log('request come', req.url); const html = fs.readFileSync('index.html', 'utf8'); res.writeHead(200, { // "Content-Type":"text/plain" "Content-Type":"text/html" }) res.end(html) }).listen(8888) console.log('server start at port 8888')
server2.js
const http = require('http'); http.createServer(function(req, res) { console.log('request come', req.url); res.writeHead(200, { // 'Access-Control-Allow-Origin':"*" // 'Access-Control-Allow-Origin':"http://localhost:8887" 'Access-Control-Allow-Origin':"http://localhost:8888" }) res.end('123') }).listen(8889) console.log('server start at port 8889')
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> 8888 <script> var xhr = new XMLHttpRequest(); xhr.open('GET','http://127.0.0.1:8889'); xhr.send(); </script> </body> </html>
"Content-Type":"text/plain" //字符串 "Content-Type":"text/html" //html
res.writeHead(200, { // 'Access-Control-Allow-Origin':"*" //容許全部 // 'Access-Control-Allow-Origin':"http://localhost:8887" // 'Access-Control-Allow-Origin':"http://localhost:8888" })
'Access-Control-Allow-Origin':"*" //容許全部 'Access-Control-Allow-Origin':"http://localhost:8887" //容許特定
利用標籤的特性html
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> 8888 <script src='http://127.0.0.1:8889'></script> </body> </html>
server2.js
const http = require('http'); http.createServer(function(req, res) { console.log('request come', req.url); res.writeHead(200, { }) res.end('123') }).listen(8889) console.log('server start at port 8889')
當用put方法時git
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> 8888 <script> var xhr = new XMLHttpRequest(); xhr.open('PUT','http://127.0.0.1:8889'); xhr.send(); </script> </body> </html>
解決辦法json
res.writeHead(200, { 'Access-Control-Allow-Origin':"*", "Access-Control-Allow-Methods":"GET,POST,PUT,DELETE" })
解決辦法瀏覽器
res.writeHead(200, { 'Access-Control-Allow-Origin':"*", "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE", "Access-Control-Allow-Max-Age":"1000", })