华清远见重庆中心——node.js个人总结

 创建一个http服务器步骤

// 引入网络通信模块
const http = require('http');
// 创建一个服务器对象
const app = http.createServer()
// 声明端口号
const port = 1024


// 绑定request事件
app.on('request', (req, res)=>{
    // req: 请求对象,客户端发送来的数据封装到该对象中
    // res: 响应对象,服务器用于做出回应的对象

    // 服务器向客户端写数据
    res.write('hello\n')
    // 结束响应并传递数据
    res.end('world')
})


// 启动服务器
app.listen(port, () => {
    // 当服务器启动成功后,就会调用此函数
    console.log(`server start: http://127.0.0.1:${port}`)
})

静态资源

什么是静态资源?

      不会发生变化的资源就是静态资源,静态资源一般指不会发生变化的文件。

静态资源服务器

const http = require('http');
const path = require('path');
const fsp = require('fs/promises');
const app = http.createServer();


// 定义静态资源文件夹
const staticDirPath = path.join(__dirname, 'public')

app.on('request', (req, res) => {
    // 拼接资源路径
    let assetPath = path.join(staticDirPath, `.${req.url}`)

    // 判断文件是否存在
    fsp.stat(assetPath).then((stat) => {
        // 判断当前路径是否是一个目录
        if (stat.isDirectory()) {
            res.setHeader('Content-Type', 'text/plain; charset=utf-8')
            res.end('无效文件')
            return
        }
        // 读取文件
        fsp.readFile(assetPath).then(data => {
            // data: 读出来的文件数据
            res.write(data)
        }).finally(() => {
            res.end()
        })
    }).catch(reason => {
        console.error(reason)
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        res.end('404资源未找到')
    })
})


app.listen(80, () => {
    console.log('server start on: http://127.0.0.1')
})

服务器跨域处理

const express = require('express');
const cors = require('cors')
const path = require("path");
const app = express()


// 若不记得跨域响应头有哪些,可以使用 cors 包
// app.use(cors())

// 添加一个中间件拦截所有请求
// app.all('*', (req, res, next) => {
//     // 设置允许跨域的响应头
//     res.setHeader('Access-Control-Allow-Origin', '*')
//     res.setHeader('Access-Control-Allow-Methods', '*')
//     res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
//     next()
// })

app.use('/', express.static(path.join(__dirname, 'public')))

app.get('/test', (req, res) => {
    res.json({msg: 'ok'})
})

app.get('/jsonp', (req, res) => {
    // const {callback} = req.query
    // res.setHeader('Content-Type', 'text/javascript')
    // const params = {x: 1, y: 2}
    // res.send(`${callback}('${JSON.stringify(params)}')`)

    res.jsonp({x: 1, y: 2})
})

app.listen(80, () => {
    console.log(`start on: http://127.0.0.1`)
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值