http协议学习相关

本文详细解析了HTTP状态码的含义及其分类,包括1xx至5xx的不同响应类型。同时深入探讨了CORS跨域请求的限制与解决方案,通过具体示例展示了如何在服务器端设置'Access-Control-Allow-Origin'以实现跨域访问。
一.HTTP CODE

定义服务器对请求的处理结果
1.100-199 代表操作要持续进行,接下来再做一些其他的事情,结果才能返回给你
2. 200-299 代表操作时成功的
3. 300-399 需要重定型,获取数据
4. 400-499 代表你发送的请求有问题,401代表你发去的请求没有认证,你是没有权限请求资源的内容的
5. 500-599 代表服务器出现了错误

二.CORS跨域请求的限制与解决

1.服务端通过’Access-Control-Allow-Origin’: '*'解决跨域问题
建立两个不同端口的文件实现跨域
server.js

const http = require('http')
const fs = require('fs')

http.createServer(function (requset, response) {
  console.log('requset come', requset.url)

  const html = fs.readFileSync('test.html', 'utf8')
  response.writeHead(200, {
    'Content-Type':'text/html'
  })
  response.end(html)
}).listen(8888)

console.log('listen 8888')

server2.js

const http = require('http')

http.createServer(function (requset, response) {
  console.log('requset come', requset.url)

  response.writeHead(200, {
    'Access-Control-Allow-Origin': '*'
  })
  response.end('123')
}).listen(8887)

console.log('listen 8887')

test.html
在该文件中进行跨域请求

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://192.168.125.118:8887/')
    xhr.send()
  </script>
</body>
</html>

2. 浏览器是允许通过link标签/script的src属性/img标签等通过url地址请求资源进行跨域的
jsonp跨域原理利用标签的属性可以通过url请求资源的原理实现跨域的

server.js内容不变
server2.js删除

response.writeHead(200, {
    'Access-Control-Allow-Origin': '*'
  })

修改test.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script src="http://192.168.125.118:8887/"></script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值