35 lines
1.2 KiB
TypeScript
35 lines
1.2 KiB
TypeScript
import {InitServerOption} from "./types";
|
|
// import { createServer as createServerOrigin } from "http";
|
|
// import express = require("express");
|
|
import * as express from "express";
|
|
|
|
export function createServer(options: Partial<InitServerOption>, callback?: () => void) {
|
|
// 创建express服务器
|
|
const app = express();
|
|
// 将请求体转换为JSON格式
|
|
app.use(express.json())
|
|
app.use(express.urlencoded({extended: true}))
|
|
// 监听端口
|
|
app.listen(options.port, callback);
|
|
// 添加允许跨域中间件
|
|
app.use(function (req, res, next) {
|
|
const method = req.method.toLowerCase();
|
|
res.header("Access-Control-Allow-Origin", "*");
|
|
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
|
|
// res.header("Access-Control-Allow-Credentials", "true");
|
|
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
|
|
if (method === 'options') {
|
|
res.status(200).end('OK');
|
|
return;
|
|
}
|
|
next();
|
|
});
|
|
|
|
app.get('/ping', (_req, res) => {
|
|
res.appendHeader('app-ping', 'pong')
|
|
res.send('pong')
|
|
})
|
|
return app;
|
|
}
|
|
|