add(server.tests.test4): 新增实验四
This commit is contained in:
2
Server/tests/test4/.gitignore
vendored
Normal file
2
Server/tests/test4/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
pnpm-lock.yaml
|
||||
44
Server/tests/test4/app.js
Normal file
44
Server/tests/test4/app.js
Normal file
@@ -0,0 +1,44 @@
|
||||
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}`);
|
||||
})
|
||||
19
Server/tests/test4/jsonp.html
Normal file
19
Server/tests/test4/jsonp.html
Normal file
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Jsonp Test</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script>
|
||||
function handleResponse(data) {
|
||||
console.log(data);
|
||||
}
|
||||
</script>
|
||||
<script src="http://localhost:3000/api/jsonp?callback=handleResponse"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
19
Server/tests/test4/package.json
Normal file
19
Server/tests/test4/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "test4",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"packageManager": "pnpm@10.14.0",
|
||||
"dependencies": {
|
||||
"body-parser": "^2.2.0",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^5.1.0",
|
||||
"express-jsonp": "^0.1.0"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user