第一步:到官网下载http://nodejs.cn/安装nodejs
第二步:安装完成后,使用npm命令安装express模块和cors模块
npm install express
npm install cors
PS:如果有使用其它模块,请自行安装.
第三步:编写以下service.js文件
//加载express框架,(一个简单的Web开发框架)
const express = require('express');
//创建一个app对象(类似一个WEB服务对象)
const app = express();
//加载cors,主要用于解决跨域问题
const cors = require('cors');
//使用到app对象上
app.use(cors());
//这里放前端项目的文件夹
app.use(express.static('Test'));
//设置访问根目录时,跳转到index.html
app.get('/',function(req,res){
res.redirect('index.html');
})
//启动服务器监听
const port = 3000;
const server = app.listen(port, function(){
console.log(`running on localhost: ${port}`);
});
最后将service.js和项目文件夹放在同一目录,然后使用命令node service.js启动即可.
后端记得处理跨域问题.至于如何处理,请使用Access-Control-Allow-Origin响应头.
PS:以上方法不知道对不对,但确实可以实现需求.如有更好的办法,请留言或评论,谢谢!