const express = require("express");
require("../db/mongoose");
const Task = require("../model/user");
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.get("/mytask",(req,res) => {
Task.find({})
.then(tasks => {
res.send(tasks);
})
.catch(e => {});
});
app.post("/mytask",res) => {
const task = new Task(req.body);
console.log(task);
task
.save()
.then(() => {
res.send(task);
})
.catch(e => {
res.status(400).send(e);
});
});
app.listen(port,() => {
console.log("Server started correcly");
});
这是我的Express App,已连接到数据库。
localhost:3000/mytask/
{
"name": "Test","description": "This is my todo"
}
这可以正常工作,并且可以在Postman中通过POST请求将数据正确存储在我的Mongodb数据库中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h1>Hello Node</h1>
<form action="/mytask" method="POST">
<input type="text" name="task" placeholder="task" />
<input type="text" name="description" placeholder="description" />
<input type="submit" />
</form>
</body>
</html>
现在我想将其连接到我的前端。但是我该怎么做呢?这是我的html文件。但是index.html不了解节点服务器。我该怎么办?