当前位置: 首页 > 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…...

从零实现富文本编辑器#5-编辑器选区模型的状态结构表达

先前我们总结了浏览器选区模型的交互策略&#xff0c;并且实现了基本的选区操作&#xff0c;还调研了自绘选区的实现。那么相对的&#xff0c;我们还需要设计编辑器的选区表达&#xff0c;也可以称为模型选区。编辑器中应用变更时的操作范围&#xff0c;就是以模型选区为基准来…...

《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)

CSI-2 协议详细解析 (一&#xff09; 1. CSI-2层定义&#xff08;CSI-2 Layer Definitions&#xff09; 分层结构 &#xff1a;CSI-2协议分为6层&#xff1a; 物理层&#xff08;PHY Layer&#xff09; &#xff1a; 定义电气特性、时钟机制和传输介质&#xff08;导线&#…...

条件运算符

C中的三目运算符&#xff08;也称条件运算符&#xff0c;英文&#xff1a;ternary operator&#xff09;是一种简洁的条件选择语句&#xff0c;语法如下&#xff1a; 条件表达式 ? 表达式1 : 表达式2• 如果“条件表达式”为true&#xff0c;则整个表达式的结果为“表达式1”…...

Android15默认授权浮窗权限

我们经常有那种需求&#xff0c;客户需要定制的apk集成在ROM中&#xff0c;并且默认授予其【显示在其他应用的上层】权限&#xff0c;也就是我们常说的浮窗权限&#xff0c;那么我们就可以通过以下方法在wms、ams等系统服务的systemReady()方法中调用即可实现预置应用默认授权浮…...

GC1808高性能24位立体声音频ADC芯片解析

1. 芯片概述 GC1808是一款24位立体声音频模数转换器&#xff08;ADC&#xff09;&#xff0c;支持8kHz~96kHz采样率&#xff0c;集成Δ-Σ调制器、数字抗混叠滤波器和高通滤波器&#xff0c;适用于高保真音频采集场景。 2. 核心特性 高精度&#xff1a;24位分辨率&#xff0c…...

面向无人机海岸带生态系统监测的语义分割基准数据集

描述&#xff1a;海岸带生态系统的监测是维护生态平衡和可持续发展的重要任务。语义分割技术在遥感影像中的应用为海岸带生态系统的精准监测提供了有效手段。然而&#xff0c;目前该领域仍面临一个挑战&#xff0c;即缺乏公开的专门面向海岸带生态系统的语义分割基准数据集。受…...

招商蛇口 | 执笔CID,启幕低密生活新境

作为中国城市生长的力量&#xff0c;招商蛇口以“美好生活承载者”为使命&#xff0c;深耕全球111座城市&#xff0c;以央企担当匠造时代理想人居。从深圳湾的开拓基因到西安高新CID的战略落子&#xff0c;招商蛇口始终与城市发展同频共振&#xff0c;以建筑诠释对土地与生活的…...

DingDing机器人群消息推送

文章目录 1 新建机器人2 API文档说明3 代码编写 1 新建机器人 点击群设置 下滑到群管理的机器人&#xff0c;点击进入 添加机器人 选择自定义Webhook服务 点击添加 设置安全设置&#xff0c;详见说明文档 成功后&#xff0c;记录Webhook 2 API文档说明 点击设置说明 查看自…...

省略号和可变参数模板

本文主要介绍如何展开可变参数的参数包 1.C语言的va_list展开可变参数 #include <iostream> #include <cstdarg>void printNumbers(int count, ...) {// 声明va_list类型的变量va_list args;// 使用va_start将可变参数写入变量argsva_start(args, count);for (in…...

苹果AI眼镜:从“工具”到“社交姿态”的范式革命——重新定义AI交互入口的未来机会

在2025年的AI硬件浪潮中,苹果AI眼镜(Apple Glasses)正在引发一场关于“人机交互形态”的深度思考。它并非简单地替代AirPods或Apple Watch,而是开辟了一个全新的、日常可接受的AI入口。其核心价值不在于功能的堆叠,而在于如何通过形态设计打破社交壁垒,成为用户“全天佩戴…...