将Node.js应用程序与前端连接(index.html)

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不了解节点服务器。我该怎么办?

pyxiaoxiao 回答:将Node.js应用程序与前端连接(index.html)

我不建议您使用res.sendFile,因为它只会发送静态HTML。您将无法将变量传递给客户端。有一个更好的解决方案称为res.render,但首先您需要配置视图引擎。 (这是ejs解决方案)

const ejs = require('ejs);
app.set('view engine','ejs');
app.set('views',__dirname + '/views');

及之后:

app.get('/url',(req,res)=>{
    res.render('yourejsFile')
})

如果您想以html扩展名写文件,可以使用

const ejs = require('ejs);
app.engine('html',ejs.renderFile)
app.set('view engine',__dirname + '/views');
,

您可以将请求从前端发送到localhost:3000, 如果要在访问localhost:3000时打开索引,请使用res.sendFile()

app.get('*',res) => {
  res.sendFile(path.join(__dirname + '/index.html'))
})

确保导入路径模块

本文链接:https://www.f2er.com/3129230.html

大家都在问