const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
// 已弃用
// const jsonp = require("express-jsonp")

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(jsonp());

const corsOptions = {
    origin: "http://127.0.0.1",
    method: ["GET", "POST"],
    allowedHeaders: ['Content-Type', "Authorization"]
}

app.use(cors(corsOptions));

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

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

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

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
})
