I am trying to send data from index.html to NodeJS server, which further will save it in MongoDB database, running locally.
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 is not in server folder. It is being run independently from different folder.
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");
})
The issue is when I click submit from index.html, it sends me POST http://localhost:3000/user net::ERR_ABORTED 400 (Bad Request)
, which is the error I have to set to throw from my server route /user
. Can you please help me understand what I am missing here?
PS: The route /user
is working as I was testing it by sending data from Postman and the data was being saved in MongoDB. Here, I am sending data in JSON and accepting in JSON too. (likewise from index.html too).
Changes: After adding console.log(req.body)
in /user
route it gives the following result to server console, when I click submit from the index.html file:
Port working
{}