Basically ı wanted to get username and password through a html file and show it in terminal using nodejs.
Here is my html codes and view
<!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>Document</title>
</head>
<body>
<h1>Registration</h1>
<form id="reg-form">
<input type="text" id="username" autocomplete="off" placeholder="Username">
<input type="password" id="password" autocomplete="off" placeholder="Password">
<input type="submit" value="Submit Form">
</form>
<script>
const form = document.getElementById('reg-form')
form.addEventListener('submit', registerUser)
async function registerUser(event){
event.preventDefault()
const username = document.getElementById('username').value
const password = document.getElementById('password').value
const result = await fetch('/api/register',{
method='POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
username,
password
})
}).then((res)=>res.json())
console.log(result)
}
</script>
</body>
</html>
And that's my nodejs file i did:
nmp install express
nmp install path
nmp install mongoose
npm install body-parser (i dont know that it is necessary. I guess right now it comes with
express module)
installation
const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
const User = require('./model/user')
mongoose.connect('mongodb://localhost:27017/login-app-db',{
useNewUrlParser:true,
useUnifiedTopology:true
})
const app = express()
app.use('/', express.static(path.join(__dirname, 'static')))
app.use(express.json())
app.post('/api/register', async(req,res)=>{
console.log(req.body)
res.json({status:'ok'})
})
app.listen(9999,()=>{
console.log('Server up at 9999')
})
And That's my user.js
const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true},
password: { type: String, required: true }
},
{collection: 'users'}
)
const model = mongoose.model('UserSchema', UserSchema)
module.exports = model
That is how i placed my files
I dont know why but i fell that fail might be about body-parser thing.
CodePudding user response:
You put a mistake here :
method='POST',
Actually, it must be :
method:'POST',
because it accepts object.