小白常犯: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访问时,返回的错误有所区别

扫描二维码关注公众号,回复: 12421070 查看本文章

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()

然而。

告辞,改日在搞~

猜你喜欢

转载自blog.csdn.net/Gragon_Shao/article/details/112643152