前后端交互系统:在Node.js中运行JavaScript

在Node.js中运行JavaScript,您需要编写适用于服务器端的代码,而不是浏览器端的代码。以下是一些示例代码,用于在Node.js中创建一个简单的HTTP服务器并在浏览器中访问它:


// 引入Node.js内置的http模块
const http = require('http');

// 创建一个HTTP服务器
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, Node.js!');
});

// 监听端口
const port = 3000;
server.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}/`);
});

将上述代码保存到一个名为main.js的文件中,然后在命令行中运行 node .\main.js。这将创建一个简单的HTTP服务器,您可以在浏览器中访问http://localhost:3000/来查看结果。

终端运行指令:

 node main.js

运作结果:

Server is running on http://localhost:3000/
在这里插入图片描述

你可能感兴趣的:(开发工具使用,1024程序员节)