1. http 模块
js
import http from 'http'
// 创建本地服务器接收数据
const server = http.createServer((req, res) => {
console.log(req.url)
res.writeHead(200, {
'Content-Type': 'application/json'
// 'Content-Type': 'text/html;charset=utf-8' // 将内容以 html 标签和 utf-8 的形式展示到网页上
})
// write 中的内容直接展示到网页上
// res.write('hello')
res.end(JSON.stringify({
data: "hello"
}))
})
server.listen(8000,()=> {
console.log("server is running")
})
1.1 解决跨域问题
接口 jsonp 解决跨域
js
// server.js
const http = require('http')
const url = require('url')
const app = http.createServer((req, res) => {
let urlObj = url.parse(req.url, true)
console.log(urlObj.query.callback)
switch (urlObj.pathname) {
case '/api/user':
res.end(`${urlObj.query.callback}(${JSON.stringify({name:'xxx',age:18})})`)
break
default:
res.end('404.')
break
}
})
app.listen(3000, () => {
console.log('localhost:3000')
})
js
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const oscript = document.createElement('script');
oscript.src = 'http://localhost:3000/api/user?callback=test';
document.body.appendChild(oscript);
function test(obj) {
console.log(obj)
}
</script>
</body>
</html>
CORS 解决跨域
js
// server.js
const http = require('http')
const url = require('url')
const app = http.createServer((req, res) => {
let urlObj = url.parse(req.url, true)
// console.log(urlObj.query.callback)
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
// CORS 头
'Access-Control-Allow-Origin': '*'
})
switch (urlObj.pathname) {
case '/api/user':
res.end(`${JSON.stringify({ name: 'xxx', age: 18 })}`)
break
default:
res.end('404.')
break
}
})
app.listen(3000, () => {
console.log('localhost:3000')
})
html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
fetch('http://localhost:3000/api/user')
.then(res=>res.json())
.then(res=>console.log(res))
</script>
</body>
</html>
1.2 作为客户端
Node.js 既可以做服务端开发,又可以做客户端开发。
get
html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
fetch('http://localhost:3000/api/user')
.then(res=>res.json())
.then(res=>console.log(res))
</script>
</body>
</html>
js
// get.js
const http = require('http')
const https = require('https')
const url = require('url')
const app = http.createServer((req, res) => {
let urlObj = url.parse(req.url, true)
// console.log(urlObj.query.callback)
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
// CORS 头
'Access-Control-Allow-Origin': '*'
})
switch (urlObj.pathname) {
case '/api/user':
// 现在作为客户端 去猫眼api请求数据
// 注意协议要统一:https还是http
httpget(res)
break
default:
res.end('404.')
break
}
})
app.listen(3000, () => {
console.log('localhost:3000')
})
function httpget(response) {
let data = ''
https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E7%9F%B3%E5%AE%B6%E5%BA%84&ci=76&channelId=4`,res => {
// data 是一份一份的数据收集,end 是最终收集到的所有数据
res.on('data', chunk => {
data += chunk
})
res.on('end', () => {
console.log(data)
response.end(data)
})
})
}
另一种写法:
js
// get.js
const http = require('http')
const https = require('https')
const url = require('url')
const app = http.createServer((req, res) => {
let urlObj = url.parse(req.url, true)
// console.log(urlObj.query.callback)
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
// CORS 头
'Access-Control-Allow-Origin': '*'
})
switch (urlObj.pathname) {
case '/api/user':
// 现在作为客户端 去猫眼api请求数据
// 注意协议要统一:https还是http
// data 收集好的时候调用内部传入的 cb 函数
httpget((data)=> {
res.end(data)
})
break
default:
res.end('404.')
break
}
})
app.listen(3000, () => {
console.log('localhost:3000')
})
function httpget(cb) {
let data = ''
https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E7%9F%B3%E5%AE%B6%E5%BA%84&ci=76&channelId=4`,res => {
// data 是一份一份的数据收集,end 是最终收集到的所有数据
res.on('data', chunk => {
data += chunk
})
res.on('end', () => {
console.log(data)
cb(data)
})
})
}
post
html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
fetch('http://localhost:3000/api/user')
.then(res=>res.json())
.then(res=>console.log(res))
</script>
</body>
</html>
js
// post.js
const http = require('http')
const https = require('https')
const url = require('url')
const app = http.createServer((req, res) => {
let urlObj = url.parse(req.url, true)
// console.log(urlObj.query.callback)
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
// CORS 头
'Access-Control-Allow-Origin': '*'
})
switch (urlObj.pathname) {
case '/api/user':
// 现在作为客户端 去小米优品 api 请求数据
// 注意协议要统一:https还是http
httpPost((data) => {
res.end(data)
})
break
default:
res.end('404.')
break
}
})
app.listen(3000, () => {
console.log('localhost:3000')
})
function httpPost(cb) {
let data = ''
const options = {
hostname: 'm.xiaomiyoupin.com',
port: '443', // 80 是 http 默认端口号,443 是 https 默认端口号
path: '/mtop/market/search/placeHolder',
methods: "POST",
headers: {
"Content-Type": "application/json",
}
}
const req = https.request(options, (res) => {
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
cb(data)
})
})
req.write(JSON.stringify([{}, { baseParam: { ypClient: 1 } }]))
req.end()
}