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

时间:2018-01-17 18:06:21

标签: node.js express http-headers http-status-codes

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

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

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 个答案:

答案 0 :(得分:0)

app.head(urlParam, [Function])不会向网址发出请求,它会在您的应用上定义新路由,以便它响应该网址上的HEAD个请求。

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