nodejs http/https
const http = require('http') const https = require('https') const querystring=require('querystring') //url字符串格式化模块
简单的服务器接口示例
const http = require('http') var server = http.createServer() server.on('request', (req, res) => { console.log('收到请求') if(req.url==='/'){ res.write('hello word') //向客户端发送数据,发送的数据只支持二进制数据或字符串 }else if(req.url==='/node'){ res.write('nodejs') } res.end() //关闭接口 }) server.listen(8080, () => { //指定端口号
console.log('localhost:8080')
})
//或 http.createServer((req, res) => { console.log('收到请求') if (req.url === '/') { res.setHeader('content-type','text/plain;charset=utf-8') //如果有中文应该添加响应头,告诉游览器编码格式,Content-type //或 res.writeHead(200(状态码), { //设置响应头 'content-type': 'text/plain;charset=utf-8' //编码格式
//'location':'/' //状态码设置为302,路由重定向为'/' }) res.end('hello word') } else if (req.url === '/node') { res.end('nodejs') } })
.listen(8080, () => { //指定端口号 console.log('localhost:8080') })
根据路由不同打开不同的页面
const http = require('http') const fs = require('fs') http.createServer((req, res) => { console.log('收到请求') var urlObj = new URL(req.url, 'http://localhost:8080') var router = urlObj.pathname //获取路由 var data = urlObj.searchParams //获取 ?后面的数据 console.log(data.get('key')) //通过get方法来获取value值 data.keys() //获取所有key值 data.values() //获取所有value值 var dataObj = [] data.forEach(function(value, key) { //遍历searchParams,将数据以kay:value格式保存 dataObj.push({ [key]: value }) }) if (router === '/') { fs.readFile('./index.html', function(err, data(二进制数据)) { //使用fs模块将文件数据读取出来并发送给前端 if (err) { res.setHeader('content-type', 'text/plain;charset=utf-8') res.end('数据读取失败') return } else { res.setHeader('content-type', 'text/html;charset=utf-8') res.end(data) //可发送二进制数据或字符串 } }) } else if (router === '/index') { res.setHeader('content-type','text/html;charset=utf-8') res.end('hello word') } else { res.end(req.url) } }) .listen(8080, () => { console.log('localhost:8080') })
//发送get请求 https.get('url', (result) => { let data = '' result.on('data', (chunk) => { data += chunk }) result.on('end', () => { res.writeHead(200, { 'content-type': 'application/json;charset=utf-8' }) res.write(data) res.end() }) })
//发送post请求
var postData=querystring.stringify({ name:'张三', age:18, sex:'男' }) var server=http.createServer((req,res)=>{ var request=http.request({ protocol:'http:', hostname:'localhost', method:'post', port:3000, path:'/data', headers:{ 'content-type':'application/x-www-form-urlencoded', 'Content-Lenght':Buffer.byteLength(postData) } },(result)=>{ console.log(result) }) request.write(postData) request.end() }) server.listen(8080,()=>{ console.log('localhost:8080') })

浙公网安备 33010602011771号