【发布时间】: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