//server.js const http = require('http'); const fs = require('fs');
http.createServer(function(req,res){ console.log('req come', req.url); const html = fs.readFileSync('test.html', 'utf8'); res.writeHead(200,{ 'Content-Type': 'text/html' }) res.end(html); }).listen(8888);
//server2.js const http = require('http'); http.createServer(function(req,res){ console.log('req come', req.url); res.end('123'); }).listen(8887);
然后分别启动这两个服务
<!--test.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> <script> var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://127.0.0.1:8887'); xhr.send(); </script> </body> </html>
// server2.js const http = require('http'); http.createServer(function(req,res){ console.log('req come', req.url); res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }) res.end('345'); }).listen(8887);
//server2.js const http = require('http'); http.createServer(function(req,res){ console.log('req come', req.url); res.end('345'); }).listen(8887);
<!--test.html--> <body> <!-- <script> var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://127.0.0.1:8887'); xhr.send(); </script> --> <script src="http://127.0.0.1:8887"></script> </body>