要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一、url模块:

url.parse(urlString[, parseQueryString[, slashesDenoteHost]])
  urlString url字符串
  parseQueryString 是否解析
  slashesDenoteHost 
    -默认为false,//foo/bar 形式的字符串将被解释成 { pathname: ‘//foo/bar' }
    -如果设置成true,//foo/bar 形式的字符串将被解释成 { host: ‘foo', pathname: ‘/bar' }
const url = require('url');

console.log(url.parse('https://api.xdclass.net/pub/api/v1/web/product/find_list_by_type?type=2',true))

输出结果:

 

 二、使用http模块处理GET、POST请求的难点:

就掌握下面三个方法就行

 

 三、案例:实现增删该查。 以及跨域的处理

项目结构如下: user.js是数据访问层,index.js是路由层,server.js是主程序

 

 controller/user.js:

/**
 * 这个模块用来模拟数据库的 增、删、改、查
 */
module.exports = {
    getUserList() {
        return [
            {
                id: 1,
                name: 'eric',
                city: '北京'
            },
            {
                id: 2,
                name: 'xiaoming',
                city: '广州'
            }
        ]
    },
    addUser(userObj) {
        return {
            code: 0,
            msg: '新增成功',
            data: null
        }
    },
    delectUser(id) {
        return {
            code: 0,
            msg: '删除成功',
            data: null
        }
    },
    updateUser(id, userObj) {
        return {
            code: 0,
            msg: '更新成功',
            data: null
        }
    }
}

router/index.js

/**
 * 这个模块专门用来路由请求
 * 针对不同的请求方法和路径,调用不同的方法
 */

const url = require('url')
const {getUserList, addUser, delectUser, updateUser} = require('../controller/user')

function handleRequest(req, res) {
    let urlObj = url.parse(req.url, true);
    console.log(urlObj)
    if (urlObj.pathname === '/api/getUserList' && req.method === 'GET') {
        return getUserList();
    }
    if (urlObj.pathname === '/api/addUser' && req.method === 'POST') {
        return addUser(req.body);
    }
    if (urlObj.pathname === '/api/delectUser' && req.method === 'POST') {
        return delectUser(urlObj.query.id);
    }
    if (urlObj.pathname === '/api/updateUser' && req.method === 'POST') {
        return updateUser(urlObj.query.id, req.body);
    }
}

module.exports = handleRequest

server.js

const http = require('http');
const routerModal = require('./router/index')


const getPostData = (req) => {
    /**
     * 把接收请求body的IO操作放在Promise对象中
     * 看起来更加美观,用起来也方便
     */
    return new Promise((resolve, reject) => {
        if (req.method !== 'POST') {   //如果不是POST请求,直接返回
            resolve({})
            return
        }
        let postData = '';
        req.on('data', chunk => {
            postData += chunk;
        })
        req.on('end', () => {
            console.log(postData)
            resolve(JSON.parse(postData))
        })
    })
}

const server = http.createServer((req, res) => {
    //设置允许跨域的域名,*代表允许任意域名跨域,也可以设置白名单列表
    // 什么是跨域?用户请求A地址,但A地址的后端又去请求了B地址拿数据,就需要在B地址的后端设置请求头,允许A地址的跨域
    res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5501");
    //解决浏览器汉字显示乱码问题
    res.writeHead(200, {'content-type': 'application/json;charset=UTF-8'})
    getPostData(req).then((data) => {
        req.body = data
        let resultData = routerModal(req, res);
        if (resultData) {
            res.end(JSON.stringify(resultData))
        } else {
            res.writeHead(404, {'content-type': 'text/html'})
            res.end('404 not found')
        }
    })

})

server.listen(3000, () => {
    console.log('监听3000端口')
})

 什么是跨域?

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2022-07-16 10:15  要一直走下去  阅读(233)  评论(0)    收藏  举报