在Node.js中運行JavaScript,您需要編寫適用于服務(wù)器端的代碼,而不是瀏覽器端的代碼。以下是一些示例代碼,用于在Node.js中創(chuàng)建一個簡單的HTTP服務(wù)器并在瀏覽器中訪問它:
// 引入Node.js內(nèi)置的http模塊
const http = require('http');
// 創(chuàng)建一個HTTP服務(wù)器
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
// 監(jiān)聽端口
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on http://localhost:${port}/`);
});
將上述代碼保存到一個名為main.js的文件中,然后在命令行中運行 node .\main.js。這將創(chuàng)建一個簡單的HTTP服務(wù)器,您可以在瀏覽器中訪問http://localhost:3000/來查看結(jié)果。
終端運行指令:
node main.js
運作結(jié)果:文章來源:http://www.zghlxwxcb.cn/news/detail-716428.html
Server is running on http://localhost:3000/文章來源地址http://www.zghlxwxcb.cn/news/detail-716428.html
到了這里,關(guān)于前后端交互系統(tǒng):在Node.js中運行JavaScript的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!