【问题标题】:Why does Express.js res.send(jsonObject.property) crash the app?为什么 Express.js res.send(jsonObject.property) 会使应用程序崩溃?
【发布时间】:2021-04-15 12:24:25
【问题描述】:

使用带有 JSON 对象属性的 response.send() 会使应用程序崩溃。

const express = require('express')
const https = require('https')
const app = express()

app.get('/', function(req, res) {

  const url = 'https://api.openweathermap.org/data/2.5/weather?q=London&appid=myID&units=metric'
  
  https.get(url, function(response) { 
    response.on('data', function(data){
      const weatherData = JSON.parse(data)
      const temp = weatherData.main.temp
      const weatherDescription = weatherData.weather[0].description
      res.send(temp)
    })
  })
})

app.listen(3000, () => {
  console.log('We are up and running... d(-_^)')
})

使用 nodemon 的 bash 错误消息是:

express deprecated res.send(status): Use res.sendStatus(status) instead at app.js:16:11
_http_server.js:248
    throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
    ^

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: -0.78
    at ServerResponse.writeHead (_http_server.js:248:11)
    at ServerResponse._implicitHeader (_http_server.js:239:8)
    at ServerResponse.end (_http_outgoing.js:763:10)
    at ServerResponse.send (C:path\node_modules\express\lib\response.js:221:10)
    at IncomingMessage.<anonymous> (C:path\app.js:16:11)
    at IncomingMessage.emit (events.js:311:20)
    at IncomingMessage.Readable.read (_stream_readable.js:512:10)
    at flow (_stream_readable.js:989:34)
    at resume_ (_stream_readable.js:970:3)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  code: 'ERR_HTTP_INVALID_STATUS_CODE'

有趣的是,预先使用一个字符串或简单地使用两个不同的 JSON 属性是可行的:

res.send('' + temp)

res.send(weatherDescription + temp)

Express / Node 崩溃的原因是什么?您介意解释一下为什么会这样吗?

提前谢谢你!

【问题讨论】:

  • 因为数字被假定为状态码,如 200(OK),而 -0.78 不是有效的状态码。这就是错误消息所说的内容,以及为什么您似乎在使用已弃用的方法(这种歧义可能是它被弃用的原因)。

标签: javascript node.js json api express


【解决方案1】:

the API reference:

res.send([body])
发送 HTTP 响应。

body 参数可以是 Buffer 对象、String、对象、Boolean 或 Array。例如:

您正在传递一个数字,它不是有效的值类型之一。

(以前传入一个数字作为第一个参数会设置状态代码,但现在不推荐使用该功能,因此您的第一行输出)。


有趣的是事先使用字符串

someString + someNumber 会给你一个字符串,它是有效值类型之一。

【讨论】:

    【解决方案2】:

    好吧,当您指定 number 时, res.send() 快递需要一个有效的状态码。在这种情况下,您放置的 temp -0.78 不是有效的状态代码。但是当您指定一个'' 或一个string 或在表达式转换为字符串之后。这被视为有效响应而不是状态代码。希望能回答你的问题。

    let n = "3"+4
    console.log(typeof n)
    

    尝试运行这个 sn-p。你会明白为什么它会被转换成字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-24
      • 2018-04-03
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多