NodeJS跨域问题CORS②


✨文章有误请指正,如果觉得对你有用,请点三连一波,蟹蟹支持😘

                    ⡖⠒⠒⠒⠤⢄⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸   ⠀⠀⠀⡼⠀⠀⠀⠀ ⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢶⣲⡴⣗⣲⡦⢤⡏⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⠋⠉⠉⠓⠛⠿⢷⣶⣦⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠇⠀⠀⠀⠀⠀⠀⠘⡇⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡞⠀⠀⠀⠀⠀⠀⠀⢰⠇⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡴⠊⠉⠳⡄⠀⢀⣀⣀⡀⠀⣸⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠃⠀⠰⠆⣿⡞⠉⠀⠀⠉⠲⡏⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠈⢧⡀⣀⡴⠛⡇⠀⠈⠃⠀⠀⡗⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣱⠃⡴⠙⠢⠤⣀⠤⡾⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢀⡇⣇⡼⠁⠀⠀⠀⠀⢰⠃⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣸⢠⣉⣀⡴⠙⠀⠀⠀⣼⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡏⠀⠈⠁⠀⠀⠀⠀⢀⡇⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠃⠀⠀⠀⠀⠀⠀⠀⡼⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⣰⠃⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⣀⠤⠚⣶⡀⢠⠄⡰⠃⣠⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢀⣠⠔⣋⣷⣠⡞⠀⠉⠙⠛⠋⢩⡀⠈⠳⣄⠀⠀⠀⠀⠀⠀⠀
⠀⡏⢴⠋⠁⠀⣸⠁⠀⠀⠀⠀⠀ ⠀⣹⢦⣶⡛⠳⣄⠀⠀⠀⠀⠀
⠀⠙⣌⠳⣄⠀⡇   不能   ⡏⠀⠀  ⠈⠳⡌⣦⠀⠀⠀⠀
⠀⠀⠈⢳⣈⣻⡇   白嫖 ⢰⣇⣀⡠⠴⢊⡡⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠳⢿⡇⠀⠀⠀⠀⠀⠀⢸⣻⣶⡶⠊⠁⠀⠀
⠀⠀⠀⠀⠀⢠⠟⠙⠓⠒⠒⠒⠒⢾⡛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⠏⠀⣸⠏⠉⠉⠳⣄⠀⠙⢆⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⡰⠃⠀⡴⠃⠀⠀⠀⠀⠈⢦⡀⠈⠳⡄⠀⠀⠀⠀⠀⠀⠀
⠀⠀⣸⠳⣤⠎⠀⠀⠀⠀⠀⠀⠀⠀⠙⢄⡤⢯⡀⠀⠀⠀⠀⠀⠀
⠀⠐⡇⠸⡅⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⡆⢳⠀⠀⠀⠀⠀⠀
⠀⠀⠹⡄⠹⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣇⠸⡆⠀⠀⠀⠀⠀
⠀⠀⠀⠹⡄⢳⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⡀⣧⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢹⡤⠳⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣷⠚⣆⠀⠀⠀⠀
⠀⠀⠀⡠⠊⠉⠉⢹⡀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡎⠉⠀⠙⢦⡀⠀
⠀⠀⠾⠤⠤⠶⠒⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠒⠲⠤⠽   

前言

  1. Node.js是一个javascript运行环境。它让javascript可以开发后端程序,实现几乎其他后端语言实现的所有功能,可以与```PHP、Java、Python、.NET、Ruby等后端语言平起平坐。
  2. Nodejs是基于V8引擎,V8是Google发布的开源JavaScript引擎,本身就是用于Chrome浏览器的JS解释,但是Node之父 Ryan Dahl在这里插入图片描述把这V8搬到了服务器上,用于做服务器的软件。

NODE内置模块

   HTTP模块


W3C : https://www.w3schools.cn//W3C

Node:https://nodejs.cn/api/http.html

功能:创建服务器

创建简单的服务器

var http = require("http")

//创建服务器
http.createServer((req, res) => {
    //req 接受浏览器传的参数 
    //res 返回渲染的内容

    res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" })
    res.write(`
      <html>
          <b>hello wolrd</b>
          <div>大家好</div>
      </html>
    `)
    res.end()
}).listen(8080, () => {
    console.log("server start http://127.0.0.1:8080/")
})

不同接口返回不同界面

var http = require("http")
//创建服务器

var server = http.createServer()

server.on("request", (req, res) => {
    //req 接受浏览器传的参数 
    //res 返回渲染的内容

    if (req.url === "/favicon.ico") {
        // todo 读取本地图标
        return
    }
    res.writeHead(renderStatus(req.url), { "Content-Type": "text/html;charset=utf-8" })
    res.write(renderHTML(req.url))
    res.end()
})

server.listen(8080, () => {
    console.log("server start http://127.0.0.1:8080/")
})

function renderHTML(url) {

    switch (url) {
        case "/home":
            return `
            <html>        
                <div>home页面</div>
            </html>
          `
        case "/list":
            return `
            <html>
                <div>list页面</div>
            </html>
          `
        case "/api/list":
            return `
            ["list1","list2","list3"]
          `
        case "/api/home":
            return `
            {name:"kerwin"}
          `
        default:
            return `
            <html>
                <div>not found</div>
            </html>
          `
    }

}

function renderStatus(url) {
    var arr = ["/home", "/list", "/api/home", "/api/list"]
    return arr.includes(url) ? 200 : 404
}

JSONP解决跨域问题

客户端

<!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>
    <!-- jsonp接口调用 -->

    <script>
        var oscript = document.createElement("script")
        oscript.src = "http://localhost:8080/api/As?callback=test"

        document.body.appendChild(oscript)


        function test(obj) {
            console.log(obj)
        }
    </script>
</body>

</html>

服务器

var http = require("http")
var url = require("url")

http.createServer((req, res) => {
    var urlobj = url.parse(req.url, true)
    console.log(urlobj.query.callback)
    switch (urlobj.pathname) {
        case "/api/As":
            res.end(`${urlobj.query.callback} (${JSON.stringify({
                name: "kerwin",
                age: 100
            })})`)
            break;
        default:
            res.end("404")
    }
}).listen(8080, () => {
    console.log("server start http://127.0.0.1:8080/")
})

CORS解决跨域问题

客户端

<!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:8080/api/As")
            .then(res => res.json())
            .then(res => {
                console.log(res)
            })
    </script>
</body>

</html>

服务器


var http = require("http")
var url = require("url")

http.createServer((req, res) => {
    var 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/As":
            res.end(`${JSON.stringify({
                name: "kerwin",
                age: 100
            })}`)
            break;
        default:
            res.end("404")
    }
}).listen(8080, () => {
    console.log("server start http://127.0.0.1:8080/")
})

HTTP客户端模块~Get

客户端

<!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/As").then(res => res.json()).then(res => {
            console.log(res)
        })
    </script>
</body>

</html> 

服务器

var http = require("http")
var https = require("https")
var url = require("url")

http.createServer((req, res) => {
    var urlobj = url.parse(req.url, true)

    res.writeHead(200, {
        "Content-Type": "application/json;charset=utf-8",
        //cors头,
        "access-control-allow-origin": "*"
    })

    switch (urlobj.pathname) {
        case "/api/As":
            // 客户端 去猫眼要数据
            httpget((data) => {
                res.end(data)
            })
            break;
        default:
            res.end("404")
    }
}).listen(3000, () => {
    console.log('http://127.0.0.1:3000');
})


function httpget(cb) {
    var data = ""
    https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E5%8C%97%E4%BA%AC&ci=1&channelId=3`, (res) => {
        res.on("data", (chunk) => {
            data += chunk
        })

        res.on("end", () => {
            console.log(data)
            cb(data)
        })
    })
}

HTTP客户端模块~Post

Node Https : https://nodejs.cn/api/https.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:8080/api/As")
            .then(res => res.json())
            .then(res => {
                console.log(res)
            })
    </script>
</body>

</html>

服务器

var http = require("http")
var https = require("https")
var url = require("url")

http.createServer((req, res) => {
    var 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/As":
            //客户端 去小米优品要数据
            httppost((data) => {
                res.end(data)
            })
            break;
        default:
            res.end("404")
    }
}).listen(8080)


function httppost(cb) {
    var data = ""

    var options = {
        hostname: "m.xiaomiyoupin.com", //域名
        port: "443", //端口
        path: "/mtop/market/search/placeHolder", //地址
        method: "POST", //请求方法
        headers: {
            "Content-Type": "application/json"
            // "Content-Type":"x-www-form-urlencoded" 
        }
    }
    var req = https.request(options, (res) => {
        res.on("data", chunk => {
            data += chunk
        })
        res.on("end", () => {
            cb(data)
        })
    })
    // req.write("name=kerwin&age=100")
    req.write(JSON.stringify([{}, { "ypClient": 3 }]))
    req.end()
}

HttpCheerio模块蜘蛛

GitHub : https://github.com/cheeriojs/cheerio

服务器

var http = require("http")
var https = require("https")
var url = require("url")

var cheerio = require("cheerio")

http.createServer((req, res) => {
    var urlobj = url.parse(req.url, true)

    res.writeHead(200, {
        "Content-Type": "application/json;charset=utf-8",
        //cors头,
        "access-control-allow-origin": "*"
    })

    switch (urlobj.pathname) {
        case "/api/As":
            //客户端 去猫眼要数据
            httpget((data) => {
                res.end(spider(data))
            })
            break;
        default:
            res.end("404")
    }
}).listen(8080, () => {
    console.log('http://127.0.0.1:8080');
})


function httpget(cb) {
    var data = ""
    https.get(`https://i.maoyan.com/`, (res) => {
        res.on("data", (chunk) => {
            data += chunk
        })

        res.on("end", () => {
            cb(data)
        })

    })
}

function spider(data) {
    // npm i cheerio 
    let $ = cheerio.load(data)

    let $moviewlist = $('.mb-outline-b.content-wrapper')
    console.log($moviewlist)
    let movies = []

    $moviewlist.each((index, value) => {
        movies.push({
            title: $(value).find(".title").text(),
            grade: $(value).find(".grade").text(),
            actor: $(value).find(".actor").text()
        })
    })

    return JSON.stringify(movies)
}

效果

在这里插入图片描述

总结

以上是个人学习Node的相关知识点,一点一滴的记录了下来,有问题请评论区指正,共同进步,这才是我写文章的原因之,如果这篇文章对您有帮助请三连支持一波

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SYFStrive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值