[英]Why does Express.js res.send(jsonObject.property) crash the app?
使用带有 JSON object 属性的 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崩溃的原因是什么? 你介意解释一下为什么会这样吗?
先感谢您!
请参阅API 参考:
res.send([正文])
发送 HTTP 响应。主体参数可以是缓冲区 object、字符串、object、Boolean 或数组。 例如:
您正在传递一个数字,它不是有效的值类型之一。
(以前传入一个数字作为第一个参数会设置状态代码,但现在不推荐使用该功能,因此您的第一行输出)。
有趣的是,事先使用字符串
someString + someNumber 会给你一个字符串,它是有效的值类型之一。
好吧,当您指定数字时, res.send() 快递需要一个有效的状态码。 在这种情况下,您输入的 temp -0.78
不是有效的状态代码。 但是当你指定一个''
或者一个string
或者在表达式被转换成一个字符串之后。 这被视为有效响应而不是状态代码。 希望这能回答你的问题。
let n = "3"+4
console.log(typeof n)
尝试运行此代码段。 您将看到为什么将其转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.