前端简单搭建koa,express服务器

不管哪种都需要安装nodejs

关于koa服务器

//需要安装npm i koa以及npm i koa-router
//引用相应的
const Koa = require('koa');
const router = require('koa-router')();
const app = new Koa();
//解决跨域
const cors = require('koa-cors');

router.post('/signin', async (ctx, next) => {
    ctx.response.body = 'Hello World';
});

app.use(cors());
app.use(router.routes());

app.listen(3000);

关于express服务器

//安装npm i express
var express = require('express');
var app = express();

//允许访问,解决跨域
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.header('Access-Control-Allow-Headers','Content-Type,Content-Length,Authorization,\'Origin\',Accept,X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('X-Powered-By', ' 3.2.1');
    res.header('Content-Type', 'application/json;charset=utf-8');
	next();
})

//接口
app.post('/signin',function(req,res){
	res.send('输出需要返回的内容')
})

var server = app.listen(3000, function () {
	var host = server.address().address
	var port = server.address().port
	
	console.log("应用实例,访问地址为 http://%s:%s", host, port)
})

 

你可能感兴趣的:(前端)