账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    node.js怎么发带请求头的get请求?
    40
    0
    http.get('url',function(res){
            
           var html = ''
            
           res.on('data',function(chunk){
                  html += chunk
           })
           
           res.on('end',function(){
                  console.log(html)
           })
           
    })
    
    
    
    //这样写好像并不行
    const options = {
         url:'xxxx'
         a:'asdsaf',
         fsa:'asioduioasd'
    }
    http.get(options,function(res){
    ...
    })
    

    我想给url地址发送带特定请求头的请求,请问,如何在这个里面设置请求头呢?

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 我就是最帅气 普通会员 1楼

      在Node.js中,你可以使用内置的http或第三方库如axiosrequestnode-fetch等来发送带请求头的GET请求。以下是使用httpaxios的示例:

      1. 使用Node.js内置的http模块:

      ```javascript const http = require('http');

      const options = { hostname: 'example.com', port: 80, path: '/path', method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token' } };

      const req = http.request(options, (res) => { let data = '';

      res.on('data', (chunk) => { data += chunk; });

      res.on('end', () => { console.log(data); }); });

      req.on('error', (error) => { console.error(Problem with request: ${error.message}); });

      req.end(); ```

      1. 使用axios库:

      首先需要安装axios:npm install axios

      ```javascript const axios = require('axios');

      axios.get('https://example.com/path', { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token' } }) .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); }); ```

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部