柚子快报邀请码778899分享:node.js [ERR

http://yzkb.51969.com/

问题描述

如果你的node.js提示:[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

那么,代表你返回了结果,但是最后你又不小心再返回了一次。通常是由于方法没有进行等待,或者多条件判断缺漏造成的。

解决方案:

情况一:返回机制问题

通过success/error模式来返回结果,取消最终的默认返回;

或者通过await方法返回再return结果即可。

axios.get(optionsEntitlement.url,{headers,httpsAgent})

// axios.get(optionsEntitlement.url,optionsEntitlement)

.then(function (response) {

// handle success

console.log("entitlement success:"+response);

res.status(200).send(response)

}).catch(function (error) {

// handle error

console.log("entitlement error:"+error);

res.status(500).send({

"message": {

"code": "AIE0001",

"type": "E",

"timestamp": new Date().toISOString(),

"text": "System Unavailable",

error

}

});

});

// res.json({ title: 'LMD GCS Node - entitlement' });

});

情况二:

服务器会输出响应头,再输出主体内容,如果你在代码中设置了res.writeHead()函数,然后再使用res.send()方法,就会出现这个错误。通常要使用res.end()

const body = 'hello https://zhengkai.blog.csdn.net/';

response

.writeHead(200, {

'Content-Length': Buffer.byteLength(body),

'Content-Type': 'text/json;charset=utf-8',

})

.end(body);

认识 Express 的 res.send() 和 res.end()

相同点

Express 的 res.end() 和 res.send() 方法的相同点:

二者最终都是回归到 http.ServerResponse.Use 的 response.end() 方法。二者都会结束当前响应流程。

不同点

Express 的 res.end() 和 res.send() 方法的不同点:

前者只能发送 string 或者 Buffer 类型,后者可以发送任何类型数据。从语义来看,前者更适合没有任何响应数据的场景,而后者更适合于存在响应数据的场景。

总结

Express 的 res.end() 和 res.send() 方法使用上,一般建议使用 res.send()方法即可,这样就不需要关心响应数据的格式,因为 Express 内部对数据进行了处理。

柚子快报邀请码778899分享:node.js [ERR

http://yzkb.51969.com/

相关链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: