Node/Express - 如何发送获取请求来检查状态码

Node/Express - How to send get request to check a status code

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

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

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')
})

最令人费解的是,此处显示的代码在周五运行。昨晚试了下,不行。任何见解将不胜感激。

app.head(urlParam, [Function]) 不会向 url 发出请求,它会在您的应用程序上定义一个新路由,以便它响应 HEAD 对 url 的请求.

要检查 URL 是否存在,您需要使用另一个包来发出请求。我的最爱之一是 Request。要使用它,只需将 app.head 替换为 request 并将 require('request') 添加到文件顶部。