小白常犯:nodejs使用http请求baidu.com,返回400错误

问题:nodejs使用http请求baidu.com,返回400错误,如下图

 

vscode:nodejs

const http = require('http')

const option = {
    hostname: 'baidu.com',
    port: 443,
    path: '/',
    method: 'GET',
}

const req = http.request(option, res => {
  res.on('data', d => {
      process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(error)
})

req.end()

 

原因:请求baidu.com的时候需要在前面补全www,并且http请求使用的是80端口

 

改正后的nodejs代码

const https = require('https')

const option = {
    hostname: 'www.baidu.com',
    port: 80,
    path: '/',
    method: 'GET',
}

const req = https.request(option, res => {
  res.on('data', d => {
      process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(error)
})

req.end()

 

使用了80端口,但是没改成www,那么百度会返回一个网页,上面带着正确的地址,chrome会自动访问到正确的网址

改了端口号,没有该WWW的返回结果

 

改正后的返回结果

 

更多

我们请求的时候,还是使用https好了,现在的大网站很多都不能用http访问了

但是不同给的网站在使用http访问时,返回的错误有所区别

http://www.zhihu.com:80

你没看错,我也不知道为什么用http访问知乎既没有报错,也没有输出

http://www.csdn.net:80   返回301

http://www.bilibili.com:80 返回301

http://www.qq.com:80

http://www.taobao.com:80

除了在node上测试这些端口,我还在chrome上测试了一下http://www.taobao.com:80

结果出乎我的意料

在chrome上摁F12 进入控制台,地址栏输入http://www.taobao.com:80

http://www.taobao.com:80

chrome 请求了两次,第一次使用的是我们输入的方式,淘宝返回了307(与我们使用node获得的返回码不同)

在获得了307错误后,chrome自动调用了https去请求淘宝

https://www.taobao.com:443

探究:为什么使用chrome访问淘宝返回的是307而不是301

猜测,chrome自带了一些headers,是这些不同导致的

验证代码:

const http = require('http')

const option = {
    hostname: 'www.taobao.com',
    port: 80,
    path: '/',
    method: 'GET',
    headers:{
        'Upgrade-Insecure-Requests': 1,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' + 
                      'AppleWebKit/537.36 (KHTML, like Gecko)' + 
                      'Chrome/87.0.4280.141 ' + 
                      'Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;' + 
                  'q=0.9,image/avif,image/webp,image/apng,*/*;' + 
                  'q=0.8,application/signed-exchange;' + 
                  'v=b3;' + 
                  'q=0.9',
    }
}

const req = http.request(option, res => {
  res.on('data', d => {
      process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(error)
})

req.end()

 

然而。

 

告辞,改日在搞~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值