NodeJS跨域问题CORS②

文章目录

  • ✨文章有误请指正,如果觉得对你有用,请点三连一波,蟹蟹支持
  • 前言
  • NODE内置模块
  •    HTTP模块
    • 创建简单的服务器
    • 不同接口返回不同界面
    • JSONP解决跨域问题
    • CORS解决跨域问题
    • HTTP客户端模块~Get
    • HTTP客户端模块~Post
    • HttpCheerio模块蜘蛛
  • 总结


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

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

前言

  1. Node.js是一个javascript运行环境。它让javascript可以开发后端程序,实现几乎其他后端语言实现的所有功能,可以与```PHP、Java、Python、.NET、Ruby等后端语言平起平坐。
  2. Nodejs是基于V8引擎,V8是Google发布的开源JavaScript引擎,本身就是用于Chrome浏览器的JS解释,但是Node之父 Ryan DahlNodeJS跨域问题CORS②_第1张图片把这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(`
      
          hello wolrd
          
大家好
`
) 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 `
                    
                
home页面
`
case "/list": return `
list页面
`
case "/api/list": return ` ["list1","list2","list3"] ` case "/api/home": return ` {name:"kerwin"} ` default: return `
not found
`
} } 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)
}

效果

NodeJS跨域问题CORS②_第2张图片

总结

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

你可能感兴趣的:(NODEJS,javascript,前端,开发语言)