Skip to main content

应用场景

静态资源

静态资源是指不需要经过服务器处理的资源,比如图片、CSS、JavaScript 等文件。这些资源的请求不需要经过服务器,直接返回给浏览器即可。

它一定发起了 HTTP 请求吗?

不一定,浏览器会根据资源的类型,决定是否发起 HTTP 请求。

跨域

跨域是指浏览器的同源策略限制了不同源的 HTTP 请求。它的目的是为了保证用户信息的安全,防止恶意的网站窃取数据。

同源策略是指,协议、域名、端口相同,才是同源。

登录

登录是指用户输入用户名和密码,然后服务器验证通过后,返回一个凭证给浏览器。浏览器将凭证保存起来,后续的请求都会带上这个凭证,服务器就可以知道这个请求是哪个用户发起的。

登陆时,有哪些 HTTP 动作?

  • GET:获取登录页面
  • POST:提交用户名和密码
  • GET:获取登录成功后的页面

发起 HTTP 协议

XHR

XHR (XMLHttpRequest)是浏览器提供的 API,用于发起 HTTP 请求。

下面是一个 JS 代码片段,用于发起一个 GET 请求。

const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8080')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.responseText)
}
}
}
xhr.send()

Fetch

Fetch 是浏览器提供的 API,用于发起 HTTP 请求。他可以认为是 XHR 的升级版,支持 Promise,语法更加简洁。

下面是一个 JS 代码片段,用于发起一个 GET 请求。

fetch('http://localhost:8080',
{
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
)
.then(response => response.text())
.then(text => console.log(text))

Node 发起 HTTP 请求

Node 也可以发起 HTTP 请求,但是它的 API 和浏览器不一样。

下面是一个 Node 代码片段,用于发起一个 GET 请求。

const http = require('http')
const options = {
hostname: 'localhost',
port: 8080,
path: '/',
method: 'GET'
}
const req = http.request(options, res => {
console.log(`状态码: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()

axios

axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 Node.js 中。

下面是一个 JS 代码片段,用于发起一个 GET 请求。

axios.get('http://localhost:8080')
.then(function (response) {
console.log(response.data)
})
.catch(function (error) {
console.log(error)
})

网络优化

  • 减少 HTTP 请求
  • CDN 动态加速
  • 使用缓存
  • 使用 HTTP2
  • 压缩