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

浅谈 React Hooks

React Hooks 是 React 16.8 引入的一组 API&#xff0c;用于在函数组件中使用 state 和其他 React 特性&#xff08;例如生命周期方法、context 等&#xff09;。Hooks 通过简洁的函数接口&#xff0c;解决了状态与 UI 的高度解耦&#xff0c;通过函数式编程范式实现更灵活 Rea…...

国防科技大学计算机基础课程笔记02信息编码

1.机内码和国标码 国标码就是我们非常熟悉的这个GB2312,但是因为都是16进制&#xff0c;因此这个了16进制的数据既可以翻译成为这个机器码&#xff0c;也可以翻译成为这个国标码&#xff0c;所以这个时候很容易会出现这个歧义的情况&#xff1b; 因此&#xff0c;我们的这个国…...

谷歌浏览器插件

项目中有时候会用到插件 sync-cookie-extension1.0.0&#xff1a;开发环境同步测试 cookie 至 localhost&#xff0c;便于本地请求服务携带 cookie 参考地址&#xff1a;https://juejin.cn/post/7139354571712757767 里面有源码下载下来&#xff0c;加在到扩展即可使用FeHelp…...

React Native 导航系统实战(React Navigation)

导航系统实战&#xff08;React Navigation&#xff09; React Navigation 是 React Native 应用中最常用的导航库之一&#xff0c;它提供了多种导航模式&#xff0c;如堆栈导航&#xff08;Stack Navigator&#xff09;、标签导航&#xff08;Tab Navigator&#xff09;和抽屉…...

Python实现prophet 理论及参数优化

文章目录 Prophet理论及模型参数介绍Python代码完整实现prophet 添加外部数据进行模型优化 之前初步学习prophet的时候&#xff0c;写过一篇简单实现&#xff0c;后期随着对该模型的深入研究&#xff0c;本次记录涉及到prophet 的公式以及参数调优&#xff0c;从公式可以更直观…...

SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现

摘要 本论文旨在设计并实现基于 SpringBoot 和 uniapp 的 Champion 俱乐部微信小程序&#xff0c;以满足俱乐部线上活动推广、会员管理、社交互动等需求。通过 SpringBoot 搭建后端服务&#xff0c;提供稳定高效的数据处理与业务逻辑支持&#xff1b;利用 uniapp 实现跨平台前…...

Spring AI与Spring Modulith核心技术解析

Spring AI核心架构解析 Spring AI&#xff08;https://spring.io/projects/spring-ai&#xff09;作为Spring生态中的AI集成框架&#xff0c;其核心设计理念是通过模块化架构降低AI应用的开发复杂度。与Python生态中的LangChain/LlamaIndex等工具类似&#xff0c;但特别为多语…...

jmeter聚合报告中参数详解

sample、average、min、max、90%line、95%line,99%line、Error错误率、吞吐量Thoughput、KB/sec每秒传输的数据量 sample&#xff08;样本数&#xff09; 表示测试中发送的请求数量&#xff0c;即测试执行了多少次请求。 单位&#xff0c;以个或者次数表示。 示例&#xff1a;…...

LangFlow技术架构分析

&#x1f527; LangFlow 的可视化技术栈 前端节点编辑器 底层框架&#xff1a;基于 &#xff08;一个现代化的 React 节点绘图库&#xff09; 功能&#xff1a; 拖拽式构建 LangGraph 状态机 实时连线定义节点依赖关系 可视化调试循环和分支逻辑 与 LangGraph 的深…...

Python 训练营打卡 Day 47

注意力热力图可视化 在day 46代码的基础上&#xff0c;对比不同卷积层热力图可视化的结果 import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms from torch.utils.data import DataLoader import matplotlib.pypl…...