将 JSON 数据从 index.html 发送到 NodeJS 服务器

时间:2021-04-28 08:59:56

标签: javascript node.js express mongoose

我正在尝试将数据从 index.html 发送到 NodeJS 服务器,该服务器将进一步将其保存在本地运行的 MongoDB 数据库中。
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark rounded">
            <h1 class="navbar-brand" style="padding: 5px">Movie</h1>
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link">User</a>
                </li>
                <!-- <li class="nav-item">
                    <a class="nav-link" href="admin.html">Admin</a>
                </li> -->
            </ul>
        </nav>
    </div>

    <div class="container">
        <h1>User Register</h1>
        <div class="row">
            <div class="col-6">
                <form id="form">
                    <div class="mb-3">
                        <label for="email" class="form-label">Email address</label>
                        <input type="email" class="form-control" id="email" oninput="onChange(this)">
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="password" onchange="onChange(this)">
                    </div>
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
    <script>
        var obj = {};

        const onChange = (e) => {
            obj[e.id] = e.value;
        }

        document.querySelector('#submit').addEventListener('click',  (e) => {
            e.preventDefault();
            console.log(obj);
            let res = {};
            (async () => {
                const rawResponse = await fetch('http://localhost:3001/user', {
                    mode: 'no-cors',
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email: obj.email, password: obj.password })
                });
                // const content = await rawResponse.json().then(res => console.log(res)).catch(err => console.log(err));
                // res = content;
                return await rawResponse.json();
            })().then(res => console.log(res)).catch(err => console.log(err));
        });
    </script>
</body>
</html>

index.html 不在服务器文件夹中。它独立于不同的文件夹运行。
package.json

{
  "name": "nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.12.5",
    "validator": "^13.6.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

index.js

const express = require("express");
const mongoose= require("mongoose");
const validator = require("validator");

const app = express();
app.use(express.json());

mongoose.connect('mongodb://127.0.0.1:27017/movie-info', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true 
});

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        trim: true,
        lowercase: true,
        unique: true,
        validate(value) {
            if (!validator.isEmail(value)) {
                throw new Error('Email is Invalid');
            }
        }
    },

    password: {
        type: String,
        required: true,
        minLength: 7,
        trim: true,
        validate(value) {
            if (value.toLowerCase().includes('password')) {
                throw new Error('Password cannot contain "password"');
            }
        }
    }
});

const User = mongoose.model('User', userSchema);

const movieSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    date: {
        type: Date
    },
    director: {
        type: String,
        required: true
    },
    actor: {
        type: String
    },
    genre: {
        type: String,
        required: true
    },
    desc: {
        type: String
    }
});

const Movie = mongoose.model('Movie', movieSchema);

app.post('/user', async (req, res) => {
    try {
        console.log(req.body);
        const user = new User(req.body);
        await user.save();
        res.send(user);
    } catch (err) {
        res.status(400).send(err);
    }
});

app.post('/admin', async (req, res) => {
    try {
        const movie = new Movie(req.body);
        await movie.save();
        res.send(movie);
    } catch (err) {
        res.status(400).send(err);
    }
});

app.listen(3001, () => {
    console.log("Port working");
})

问题是当我从 index.html 单击提交时,它会向我发送 POST http://localhost:3000/user net::ERR_ABORTED 400 (Bad Request),这是我必须设置从我的服务器路由 /user 抛出的错误。你能帮我理解我在这里缺少什么吗?
PS:路由 /user 正在工作,因为我通过从 Postman 发送数据来测试它,并且数据被保存在 MongoDB 中。在这里,我以 JSON 格式发送数据并以 JSON 格式接受。 (同样来自 index.html)。

更改:在 console.log(req.body) 路由中添加 /user 后,当我单击 index.html 文件中的提交时,它会向服务器控制台提供以下结果:

Port working
{}

在浏览器的控制台中,我得到的错误是: Browser Console's result

0 个答案:

没有答案