当前位置: 首页 > news >正文

【Node.js】http 模块

1. http 模块

import http from 'http'
// 创建本地服务器接收数据
const server = http.createServer((req, res) => {console.log(req.url)res.writeHead(200, { 'Content-Type': 'application/json' // 'Content-Type': 'text/html;charset=utf-8'  // 将内容以 html 标签和 utf-8 的形式展示到网页上 })// write 中的内容直接展示到网页上// res.write('hello')res.end(JSON.stringify({data: "hello"}))
})
server.listen(8000,()=> {console.log("server is running")
})

1.1 解决跨域问题

接口 jsonp 解决跨域

// server.js
const http = require('http')
const url = require('url')const app = http.createServer((req, res) => {let urlObj = url.parse(req.url, true)console.log(urlObj.query.callback)switch (urlObj.pathname) {case '/api/user':res.end(`${urlObj.query.callback}(${JSON.stringify({name:'xxx',age:18})})`)breakdefault:res.end('404.')break}
})app.listen(3000, () => {console.log('localhost:3000')
})
<!-- index.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>const oscript = document.createElement('script');oscript.src = 'http://localhost:3000/api/user?callback=test';document.body.appendChild(oscript);function test(obj) {console.log(obj)}</script></body></html>

CORS 解决跨域

// server.js
const http = require('http')
const url = require('url')const app = http.createServer((req, res) => {let 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/user':res.end(`${JSON.stringify({ name: 'xxx', age: 18 })}`)breakdefault:res.end('404.')break}
})app.listen(3000, () => {console.log('localhost:3000')
})
<!-- index.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:3000/api/user').then(res=>res.json()).then(res=>console.log(res))</script></body></html>

1.2 作为客户端

Node.js 既可以做服务端开发,又可以做客户端开发。

get

<!-- index.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:3000/api/user').then(res=>res.json()).then(res=>console.log(res))</script>
</body></html>
// get.js
const http = require('http')
const https =  require('https')
const url = require('url')const app = http.createServer((req, res) => {let 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/user':// 现在作为客户端 去猫眼api请求数据// 注意协议要统一:https还是httphttpget(res)breakdefault:res.end('404.')break}
})
app.listen(3000, () => {console.log('localhost:3000')
})
function httpget(response) {let data = ''https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E7%9F%B3%E5%AE%B6%E5%BA%84&ci=76&channelId=4`,res => {// data 是一份一份的数据收集,end 是最终收集到的所有数据res.on('data', chunk => {data += chunk})res.on('end', () => {console.log(data)response.end(data)})})
}

另一种写法:

// get.js
const http = require('http')
const https =  require('https')
const url = require('url')const app = http.createServer((req, res) => {let 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/user':// 现在作为客户端 去猫眼api请求数据// 注意协议要统一:https还是http// data 收集好的时候调用内部传入的 cb 函数httpget((data)=> {res.end(data)})breakdefault:res.end('404.')break}
})
app.listen(3000, () => {console.log('localhost:3000')
})
function httpget(cb) {let data = ''https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E7%9F%B3%E5%AE%B6%E5%BA%84&ci=76&channelId=4`,res => {// data 是一份一份的数据收集,end 是最终收集到的所有数据res.on('data', chunk => {data += chunk})res.on('end', () => {console.log(data)cb(data)})})
}

post

<!-- index.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:3000/api/user').then(res=>res.json()).then(res=>console.log(res))</script></body></html>
// post.js
const http = require('http')
const https = require('https')
const url = require('url')const app = http.createServer((req, res) => {let 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/user':// 现在作为客户端 去小米优品 api 请求数据// 注意协议要统一:https还是httphttpPost((data) => {res.end(data)})breakdefault:res.end('404.')break}
})
app.listen(3000, () => {console.log('localhost:3000')
})
function httpPost(cb) {let data = ''const options = {hostname: 'm.xiaomiyoupin.com',port: '443', // 80 是 http 默认端口号,443 是 https 默认端口号path: '/mtop/market/search/placeHolder',methods: "POST",headers: {"Content-Type": "application/json",}}const req = https.request(options, (res) => {res.on('data', (chunk) => {data += chunk})res.on('end', () => {cb(data)})})req.write(JSON.stringify([{}, { baseParam: { ypClient: 1 } }]))req.end()
}

1.3 爬虫

相关文章:

【Node.js】http 模块

1. http 模块 import http from http // 创建本地服务器接收数据 const server http.createServer((req, res) > {console.log(req.url)res.writeHead(200, { Content-Type: application/json // Content-Type: text/html;charsetutf-8 // 将内容以 html 标签和 utf-8 的…...

S/4 HANA 大白话 - 财务会计-2 总账主数据

接下来看看财务模块的一些具体操作。 总账相关主数据 公司每天运转&#xff0c;每天办公室有租金&#xff0c;有水电费&#xff0c;有桌椅板凳损坏&#xff0c;鼠标损坏要换&#xff0c;有产品买卖&#xff0c;有收入。那么所有这些都得记下来。记哪里&#xff1f;记在总账里…...

Redis根据中心点坐标和半径筛选符合的数据

目录 1.启动Redis​编辑 2.导入maven依赖 3.添加redis配置 4.编写RedisService 5.使用 6.验证 1.启动Redis 2.导入maven依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifac…...

springboot 集成 zookeeper 问题记录

springboot 集成 zookeeper 问题记录 环境 springboot - 2.7.8 dubbo - 3.1.11 dubbo-dependencies-zookeeper-curator5 - 3.1.11 模拟真实环境&#xff0c;将 windows 上的 zookeeper 迁移到虚拟机 linux 的 docker 环境 failed to connect to zookeeper server 迁移到…...

java中的接口interface

一、面向对象基本概念 Java是一种面向对象的语言&#xff0c;其中「对象」就相当于是现实世界中的一个个具体的例子&#xff0c;而「类」就相当于是一个抽象的模板&#xff0c;将抽象的概念模板转化为具体的例子的过程就叫做「实例化」。 比如说人这个概念就是一个抽象化的「…...

多个git提交,只推送其中一个到远程该如何处理

用新分支去拉取当前分支的指定commit记录&#xff0c;之后推送到当前分支远程仓库实现推送指定历史提交的功能 1.查看当前分支最近五次提交日志 git log --oneline -5 2.拉取远程分支创建临时本地分支 localbranch 为本地分支名 origin/dev 为远程目标分支 git checkout …...

uniapp中input的disabled属性

uniapp中input的disabled属性&#xff1a; 小程序中兼容性好&#xff1b; 在H5中兼容性差&#xff1b; 在H5中使用uniapp的input的disabled属性&#xff0c;属性值只能是true或false&#xff0c;如果为0&#xff0c; "都会为true&#xff1b; <input class"in…...

Jmeter连接mysql数据库详细步骤

一、一般平常工作中使用jmeter 连接数据库的作用 主要包括&#xff1a; 1、本身对数据库进行测试&#xff08;功能、性能测试&#xff09;时会需要使用jmeter连接数据库 2、功能测试时&#xff0c;测试出来的结果需要和数据库中的数据进行对比是否正确一致。这时候可以通过j…...

Xcode 14.3.1build 报错整理

1、Command PhaseScriptExecution failed with a nonzero exit code 2、In /Users/XX/XX/XX/fayuan-mediator-app-rn/ios/Pods/CocoaLibEvent/lib/libevent.a(buffer.o), building for iOS Simulator, but linking in object file built for iOS, file /Users/XX/XX/XX/fayuan…...

TensorFlow入门(十三、动态图Eager)

一个图(Graph)代表一个计算任务,且在模型运行时,需要把图放入会话(session)里被启动。一旦模型开始运行,图就无法修改了。TensorFlow把这种图一般称为静态图。 动态图是指在Python中代码被调用后,其操作立即被执行的计算。 它与静态图最大的区别是不需要使用session来建立会话…...

批量执行insert into 的脚本报2006 - MySQL server has gone away

数据库执行批量数据导入是报“2006 - MySQL server has gone away”错误&#xff0c;脚本并没有问题&#xff0c;只是insert into 的批量操作语句过长导致。 解决办法&#xff1a; Navicat ->工具 ->服务器监控->mysql ——》变量 修改max_allowed_packet大小为512…...

翻译docker官方文档(残缺版)

Build with docker(使用 Docker 技术构建应用程序或系统镜像) Overview (概述) 介绍&#xff08;instruction&#xff09; 层次结构&#xff08;Layers&#xff09; The order of Dockerfile instructions matters. A Docker build consists of a series of ordered build ins…...

PySpark 概述

文章最前&#xff1a; 我是Octopus&#xff0c;这个名字来源于我的中文名--章鱼&#xff1b;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github &#xff1b;这博客是记录我学习的点点滴滴&#xff0c;如果您对 Python、Java、AI、算法有兴趣&#xff0c;可以关注我的…...

『heqingchun-ubuntu系统下Qt报错connot find -lGL解决方法』

ubuntu系统下Qt报错connot find -lGL解决方法 问题&#xff1a; Qt报错 connot find -lGL collect2:error:ld returned 1 exit status 解决方式&#xff1a; cd /usr/lib/x86_64-linux-gnu查看一下 ls | grep libGLlibGLdispatch.so.0 libGLdispatch.so.0.0.0 libGLESv2.so.…...

代码整洁之道:程序员的职业素养(十六)

辅导、学徒期与技艺 导师的重要性在职业发展中是不可低估的。尽管最好的计算机科学学位教学计划可以提供坚实的理论基础&#xff0c;但面对实际工作中的挑战&#xff0c;年轻毕业生往往需要更多指导。幸运的是&#xff0c;有许多优秀的年轻人可以通过观察和模仿他们的导师来快…...

OSPF的原理与配置

第1章 OSPF[1] 本章阐述了OSPF协议的特征、术语&#xff0c;OSPF的路由器类型、网络类型、区域类型、LSA类型&#xff0c;OSPF报文的具体内容及作用&#xff0c;描述了OSPF的邻居关系&#xff0c;通过实例让读者掌握OSPF在各种场景中的配置。 本章包含以下内容&#xff1a; …...

uni-app : 生成三位随机数、自定义全局变量、自定义全局函数、传参、多参数返回值

核心代码 function generateRandomNumber() {const min 100;const max 999;// 生成 min 到 max 之间的随机整数// Math.random() 函数返回一个大于等于 0 且小于 1 的随机浮点数。通过将其乘以 (max - min 1)&#xff0c;我们得到一个大于等于 0 且小于等于 (max - min 1…...

EF core 如何撤销对对象的更改

一般情况下 DB.SaveChanges() 就可以正常提交更改了. 但是如何撤销更改, 可以使用下面的代码. //撤销更改 //放弃更改. 防止后面的finally出错 DB.ChangeTracker.Entries().Where(e > e.Entity ! null).ToList().ForEach(e > e.State EntityState.Detached);...

以字符串mark作为分隔符,对字符串s进行分割

int main() {string s "How are you?";string mark " ";string tmp;int cur 0, first 0;//找到第一个标记while ((cur s.find_first_of(mark, cur)) ! string::npos){//获取第一个标记前的子串tmp s.substr(first, cur - first);cout << tmp …...

c++day6(菱形继承、虚继承、多态、模板、异常)

今日任务 1.思维导图 2.编程题&#xff1a; 代码&#xff1a; #include <iostream>using namespace std; /*以下是一个简单的比喻&#xff0c;将多态概念与生活中的实际情况相联系&#xff1a; 比喻&#xff1a;动物园的讲解员和动物表演 想象一下你去了一家动物园&a…...

KubeSphere 容器平台高可用:环境搭建与可视化操作指南

Linux_k8s篇 欢迎来到Linux的世界&#xff0c;看笔记好好学多敲多打&#xff0c;每个人都是大神&#xff01; 题目&#xff1a;KubeSphere 容器平台高可用&#xff1a;环境搭建与可视化操作指南 版本号: 1.0,0 作者: 老王要学习 日期: 2025.06.05 适用环境: Ubuntu22 文档说…...

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周&#xff0c;有很多同学在写期末Java web作业时&#xff0c;运行tomcat出现乱码问题&#xff0c;经过多次解决与研究&#xff0c;我做了如下整理&#xff1a; 原因&#xff1a; IDEA本身编码与tomcat的编码与Windows编码不同导致&#xff0c;Windows 系统控制台…...

FFmpeg 低延迟同屏方案

引言 在实时互动需求激增的当下&#xff0c;无论是在线教育中的师生同屏演示、远程办公的屏幕共享协作&#xff0c;还是游戏直播的画面实时传输&#xff0c;低延迟同屏已成为保障用户体验的核心指标。FFmpeg 作为一款功能强大的多媒体框架&#xff0c;凭借其灵活的编解码、数据…...

渲染学进阶内容——模型

最近在写模组的时候发现渲染器里面离不开模型的定义,在渲染的第二篇文章中简单的讲解了一下关于模型部分的内容,其实不管是方块还是方块实体,都离不开模型的内容 🧱 一、CubeListBuilder 功能解析 CubeListBuilder 是 Minecraft Java 版模型系统的核心构建器,用于动态创…...

TRS收益互换:跨境资本流动的金融创新工具与系统化解决方案

一、TRS收益互换的本质与业务逻辑 &#xff08;一&#xff09;概念解析 TRS&#xff08;Total Return Swap&#xff09;收益互换是一种金融衍生工具&#xff0c;指交易双方约定在未来一定期限内&#xff0c;基于特定资产或指数的表现进行现金流交换的协议。其核心特征包括&am…...

【python异步多线程】异步多线程爬虫代码示例

claude生成的python多线程、异步代码示例&#xff0c;模拟20个网页的爬取&#xff0c;每个网页假设要0.5-2秒完成。 代码 Python多线程爬虫教程 核心概念 多线程&#xff1a;允许程序同时执行多个任务&#xff0c;提高IO密集型任务&#xff08;如网络请求&#xff09;的效率…...

AI编程--插件对比分析:CodeRider、GitHub Copilot及其他

AI编程插件对比分析&#xff1a;CodeRider、GitHub Copilot及其他 随着人工智能技术的快速发展&#xff0c;AI编程插件已成为提升开发者生产力的重要工具。CodeRider和GitHub Copilot作为市场上的领先者&#xff0c;分别以其独特的特性和生态系统吸引了大量开发者。本文将从功…...

网站指纹识别

网站指纹识别 网站的最基本组成&#xff1a;服务器&#xff08;操作系统&#xff09;、中间件&#xff08;web容器&#xff09;、脚本语言、数据厍 为什么要了解这些&#xff1f;举个例子&#xff1a;发现了一个文件读取漏洞&#xff0c;我们需要读/etc/passwd&#xff0c;如…...

Go 语言并发编程基础:无缓冲与有缓冲通道

在上一章节中&#xff0c;我们了解了 Channel 的基本用法。本章将重点分析 Go 中通道的两种类型 —— 无缓冲通道与有缓冲通道&#xff0c;它们在并发编程中各具特点和应用场景。 一、通道的基本分类 类型定义形式特点无缓冲通道make(chan T)发送和接收都必须准备好&#xff0…...

【从零学习JVM|第三篇】类的生命周期(高频面试题)

前言&#xff1a; 在Java编程中&#xff0c;类的生命周期是指类从被加载到内存中开始&#xff0c;到被卸载出内存为止的整个过程。了解类的生命周期对于理解Java程序的运行机制以及性能优化非常重要。本文会深入探寻类的生命周期&#xff0c;让读者对此有深刻印象。 目录 ​…...