2、全局安装express-generator:
npm install express-generator -g
3、使用express创建工程
express --view=pug 工程名
4、进入工程目录
6、npm install
7、启动工程测试
npm start
跨域问题
app.js加入以下代码
//设置跨域访问
app.all(‘*‘, function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
// res.header("X-Powered-By",‘ 3.2.1‘)
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
路由代码可能需要改一下,如果请求头的Content-type设置为application/json
res.render 改为res.json
前端代码
import * as http from "http";
import * as querystring from ‘querystring‘;
export class NetWorkRequest {
public static sendRequest(userCode: string) {
var userId = userCode;
var post_data = { userId: userId }
var contents = querystring.stringify(post_data);
var options = {
hostname: "localhost",
port: 3000,
path: "?" + contents,
method: "POST",
rejectUnauthorized: false
};
var req = http.request(options, function (res) {
res.setEncoding(‘utf-8‘);
res.on("data", function (d) {
console.log("服务器返回数据:" + d)
});
});
req.on("error", function (e) {
});
req.end();
}
}