代码之家  ›  专栏  ›  技术社区  ›  luxdlux

节点/Express-如何发送get请求以检查状态代码

  •  0
  • luxdlux  · 技术社区  · 7 年前

    我正在尝试使URL更简短。我需要将给定的URL作为参数,并向该URL发送请求,以获取状态代码。如果status=200,我知道我有一个正常运行的URL,我将继续将其添加到DB并缩短它。

    问题是,当我发出请求时,连接超时。

    const express = require('express')
    const mongoose = require('mongoose')
    const cors = require('cors')
    const nofavicon = require('express-no-favicons')
    const Shortener = require('./shortener')
    const app = express()
    
    app.disable('x-powered-by')
    app.use(cors())
    app.use(nofavicon())
    app.use(express.static(__dirname + '/static'))
    
    mongoose.connect(
       process.env.MONGODB_URI || 'mongodb://heroku_x7hcc5zd:39c8i70697o7qrpjn4rd6kslch@ds123371.mlab.com:23371/heroku_x7hcc5zd'
    )
    
    app.get('/url/:urlParam(*)', (request, response) => {
      let urlParam = request.params.urlParam
      let urlRegEx = /[A-Za-z]+[://]+[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&;?#/.=]+/g
    
      if (urlRegEx.test(urlParam)) {
        let shortRandomNum = Math.floor(Math.random() * 10000).toString()
        // Shortener here refers to a mongoose Schema in external file
        let lmao = new Shortener({
          url: urlParam,
          urlmao: 'localhost:8080/lol/' + shortRandomNum,
        })
    
        // Request header from passed URL to verify legitimacy
        // Check statusCode and end request.
        app.head(urlParam, (req, res) => {
          let end = res.end
          // Override standard res.end function with custom function
          res.end = () => {
            if (res.statusCode == 200) {
              lmao.save((error) => {
                if (error) {
                  response.send('Unable to write to collection')
                }
              })
              console.log('pass')
              response.json({lmao})
            }
          }
          res.end = end
          res.end()
        })
    
      } else {
        // If passed URL does not satisfy regEx, return error message.
        urlParam = 'unfunny url. http(s):// prefix required. check url and retry.'
        console.log('invalid url')
    
        response.json({
          url: urlParam,
        })
      }
    })
    
    app.listen(process.env.PORT || 8080, () => {
    console.log('live connection')
    })
    

    最令人兴奋的是,这里显示的代码在星期五起作用。昨晚测试过了,没有骰子。如有任何见解,我们将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  0
  •   FSeidl    7 年前

    app.head(urlParam, [Function]) 不向url发出请求,而是在应用程序上定义新路由,以便响应 HEAD 该url上的请求。

    要检查URL是否处于活动状态,需要使用另一个包发出请求。我最喜欢的是 Request . 要使用它,只需替换 app.head 具有 request 并添加 require('request') 到文件的顶部。