Skip to content

Commit 5d99fbd

Browse files
author
浪里行舟
authored
Add files via upload
1 parent 834f831 commit 5d99fbd

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<!DOCTYPE html>
2+
<html lang="zh-CN">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
7+
<title>Node中间件代理</title>
8+
</head>
9+
10+
<body>
11+
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
12+
<script>
13+
$.ajax({
14+
url: 'http://localhost:3000',
15+
type: 'post',
16+
data: { name: 'xiamen', password: '123456' },
17+
contentType: 'application/json;charset=utf-8',
18+
success: function(result) {
19+
console.log('result', result)
20+
},
21+
error: function(msg) {
22+
console.log(msg)
23+
}
24+
})
25+
</script>
26+
</body>
27+
</html>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const http = require('http')
2+
// 第一步:接受客户端请求
3+
const server = http.createServer((request, response) => {
4+
// 代理服务器,直接和浏览器直接交互,需要设置CORS 的首部字段
5+
response.writeHead(200, {
6+
'Access-Control-Allow-Origin': '*',
7+
'Access-Control-Allow-Methods': '*',
8+
'Access-Control-Allow-Headers': 'Content-Type'
9+
})
10+
// 第二步:将请求转发给服务器
11+
const proxyRequest = http
12+
.request(
13+
{
14+
host: '127.0.0.1',
15+
port: 4000,
16+
url: '/',
17+
method: request.method,
18+
headers: request.headers
19+
},
20+
serverResponse => {
21+
// 第三步:收到服务器的响应
22+
var body = ''
23+
serverResponse.on('data', chunk => {
24+
body += chunk
25+
})
26+
serverResponse.on('end', () => {
27+
console.log('The data is ' + body)
28+
// 第四步:将响应结果转发给浏览器
29+
response.end(body)
30+
})
31+
}
32+
)
33+
.end()
34+
})
35+
server.listen(3000, () => {
36+
console.log('The proxyServer is running at http://localhost:3000')
37+
})
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const http = require('http')
2+
const data = { title: 'fontend', password: '123456' }
3+
const server = http.createServer((request, response) => {
4+
if (request.url === '/') {
5+
response.end(JSON.stringify(data))
6+
}
7+
})
8+
server.listen(4000, () => {
9+
console.log('The server is running at http://localhost:4000')
10+
})

0 commit comments

Comments
 (0)