自學(xué)網(wǎng)站建設(shè)需要什么學(xué)歷關(guān)鍵詞排名點(diǎn)擊軟件首頁(yè)
在Node.js中運(yùn)行JavaScript,您需要編寫(xiě)適用于服務(wù)器端的代碼,而不是瀏覽器端的代碼。以下是一些示例代碼,用于在Node.js中創(chuàng)建一個(gè)簡(jiǎn)單的HTTP服務(wù)器并在瀏覽器中訪(fǎng)問(wèn)它:
// 引入Node.js內(nèi)置的http模塊
const http = require('http');// 創(chuàng)建一個(gè)HTTP服務(wù)器
const server = http.createServer((req, res) => {res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('Hello, Node.js!');
});// 監(jiān)聽(tīng)端口
const port = 3000;
server.listen(port, () => {console.log(`Server is running on http://localhost:${port}/`);
});
將上述代碼保存到一個(gè)名為main.js的文件中,然后在命令行中運(yùn)行 node .\main.js。這將創(chuàng)建一個(gè)簡(jiǎn)單的HTTP服務(wù)器,您可以在瀏覽器中訪(fǎng)問(wèn)http://localhost:3000/來(lái)查看結(jié)果。
終端運(yùn)行指令:
node main.js
運(yùn)作結(jié)果:
Server is running on http://localhost:3000/