吴牛牛 發表於 2020-12-21 17:07:00

Node.js 返回 JSON 数据

<h1 id="nodejs-返回-json-数据">Node.js 返回 JSON 数据</h1>
<h2 id="requestenddata-encoding-callback">request.end(][, callback])</h2>
<pre><code class="language-js">var http = require('http');

const log = console.log;

http.createServer(function (request, response) {
    // log(`pagehide event`, request)
    // log(`pagehide event`, request.headers)
    // log(`pagehide event`, request.rawHeaders)
    // log(`page visibility`, request)
    log(`page visibility`)
    // 发送 HTTP 头部
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    // response.writeHead(200, {'Content-Type': 'text/plain'});
    response.writeHead(200, {'Content-Type': 'application/json'});

    // 发送响应数据 "Hello World"
    // response.end('Hello World\n');
    response.end(JSON.stringify({
      name: "server",
      age: 2020,
    }));
    // .json
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

</code></pre>
<p><img src="https://img2020.cnblogs.com/blog/740516/202012/740516-20201221170851995-1212245924.png" alt="" loading="lazy"></p>
<p>https://nodejs.org/api/http.html#http_request_end_data_encoding_callback</p>
<p>https://nodejs.org/api/http.html#http_request_write_chunk_encoding_callback</p>
<h2 id="refs">refs</h2>
<hr>
<div>

</div>
<hr>
<blockquote style="display: flex; flex-flow: column; align-items: center; justify-content: center; text-align: center; border: none">
<h3><strong><span style="font-size: 16pt; color: rgba(0, 255, 0, 1)">©xgqfrms 2012-<span data-uid="copyright-aside">2020</span></span></strong>
<p><span style="font-size: 18pt; color: rgba(0, 255, 0, 1)"><strong>www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!</strong></span></p>
</h3></blockquote>
<hr>


</div>
<div id="MySignature" role="contentinfo">
    <div style="display: flex; flex-flow: column nowrap; align-items: center; justify-content: center;">
<p>本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14168864.html</p>
<p style="color: red; font-size: 23px; margin-top: 5px; margin-botom: 5px;">未经授权禁止转载,违者必究!</P>
</div>
<hr/><br><br>
来源:https://www.cnblogs.com/xgqfrms/p/14168864.html
頁: [1]
查看完整版本: Node.js 返回 JSON 数据