接口大赛1

node

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');

const app = new Koa();
const router = new Router();

// 使用 bodyParser 中间件解析请求体
app.use(bodyParser());

// 使用 koa2-cors 中间件解决跨域问题
app.use(
  cors({
    origin: '*', // 允许跨域的源,可以设置为具体的域名或 IP
    maxAge: 5, // 对 OPTIONS 预检请求的缓存时间
    credentials: true, // 允许请求携带 cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 允许的 HTTP 请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], // 允许的头部信息
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], // 暴露的头部信息
  }),
);

// GET 请求
router.get('/users/:id', (ctx) => {
  const id = ctx.params.id;
  const data = ctx.request.query;
  console.log(`GET 请求已接收,携带数据为: ${JSON.stringify(data)}`);
  ctx.body = `Get user with ID ${id}`;
});

// POST 请求
router.post('/users', (ctx) => {
  const { name, age } = ctx.request.body;
  console.log(`POST 请求已接收,携带数据为: ${JSON.stringify({ name, age })}`);
  ctx.body = { name, age };
});

// DELETE 请求
router.delete('/users/:id', (ctx) => {
  const id = ctx.params.id;
  const data = ctx.request.query;
  console.log(`DELETE 请求已接收,携带数据为: ${JSON.stringify(data)}`);
  ctx.body = `Delete user with ID ${id}`;
});

// PATCH 请求
router.patch('/users/:id', (ctx) => {
  const id = ctx.params.id;
  const { name, age } = ctx.request.body;
  console.log(
    `PATCH 请求已接收,携带数据为: ${JSON.stringify({ id, name, age })}`,
  );
  ctx.body = { id, name, age };
});

app.use(router.routes());

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

接口

http://localhost:3000/users/123?name=wangfeng—get

http://localhost:3000/users—post

{
  "name": "wangfeng",
  "age":"19"
}

http://localhost:3000/users/123?name=wangfeng—delete

http://localhost:3000/users/123 —patch

你可能感兴趣的:(javascript,前端,开发语言)