const express = require('express');
const Bodyparser = require('body-parser');
const cors = require('cors');
// const jsonp = require('express-jsonp');
const app = express();


const corsOptions = {
    origin: 'http://localhost',
    methods: ['GET', 'POST'],
    allowedHeaders: ['Content-Type', 'Authorization','jsonp']
};

app.use(Bodyparser.urlencoded({ extended: true }));
app.use(Bodyparser.json());
app.use(cors(corsOptions));
// app.use(jsonp());


app.get('/api/data', (req, res) => {
    const data = [
        { id: 1, name: "张三", age: 20, gender: "男" },
        { id: 2, name: "李四", age: 22, gender: "女" }
    ];
    res.send(data);
});


app.post('/api/data', (req, res) => {
    const newData = req.body;
    console.log("Recevied new data: ", newData);
    res.status(201).json({ msg: '已添加', data: newData });
})


app.get('/api/jsonp', (req, res) => {
    const data = [
        { id: 1, name: "张三", age: 20, gender: "男" },
        { id: 2, name: "李四", age: 22, gender: "女" },
    ];
    res.jsonp(data);
})

const port = 3000;
app.listen(port, () => {
    console.log(`服务器启动成功，端口号为${port}`);
})