how to send data from frontend to backend with node js - node.js

Frontend
I use ejs to create forms
<form action="/users/create" method="POST">
<div class="row">
<div class="col-2">
Id Advance Requisition
</div>
<div class="col-6">
<input type="text" class="form-control" id="IdAdvanceRequisition" name="IdAdvanceRequisition" required/>
</div>
</div>
<div class="row">
<div class="col-2">
NoRef
</div>
<div class="col-6">
<input type="text" class="form-control" id="NoRef" name="NoRef" required/>
</div>
</div>
<div class="row">
<div class="col-2">
NIK
</div>
<div class="col-6">
<input type="text" class="form-control" id="Nik" name="Nik" required/>
</div>
</div>
<input type="hidden" class="id" name="id" />
Back
<button type="submit" class="btn btn-primary btn-sm">Save</button>
</form>
router for the router on the frontend, why can I only use post and get? whereas to delete and update you have to use DELETE and PUT
const express = require('express');
const user = require('../controllers/user')
var cors = require('cors')
const router = express.Router();
router.get('/index', user.getUsers);
router.get('/add', user.getAdd);
router.post('/create',cors (), user.createUsers);
router.get('/detail/:id', user.readUsers);
router.post('/delete/:id', cors (), user.deleteUsers);
router.get('/edit/:id', user.detailUpdate);
router.post('/update/:id',cors (), user.updateUsers);
module.exports = router;
controllers for add
createUsers : async (req,res) => {
try {
const Backend = await getBackend();
const dataBackend = await Backend.json();
const user = {id: uuidv4(), IdAdvanceRequisition: req.body.IdAdvanceRequisition, NoRef: req.body.NoRef, Nik: req.body.Nik};
dataBackend.push({...user, id: uuidv4()});
fetch('http://localhost:8000/users', {
method: 'post',
body: JSON.stringify(user)
})
console.log(`Data with the id: ${user.id} added to the database!`);
res.redirect('/users/index');
} catch (error) {
res.send(`data error`);
}
}
Results
[{"id":"3cc4ed6e-5974-4661-ade7-ec448ac0e7e3"}]
Problem: I tried to send all data to the backend, but only the UUID was sent. How can I solve this problem

Related

how to use one ejs template for updating and showing info from mongoose/mongodb?

this is my app.js file for showing and updating info for my posts in one single Ejs template called compose: when I run my code I get this error
**
SyntaxError: missing ) after argument list in C:\Users\john\Desktop\blog\views\compose.ejs while compiling ejs**
app.post("/compose", function (req, res) {
var title= req.body.postTitle
var content= req.body.postText
const post = new Post({
title: title,
content: content
});
post.save(function(err){
if (!err){
res.redirect("/");
}
});
// res.redirect("/");
});
// update posts
app.get('/update/:postid', function (req, res) {
const updateId = req.params.postid;
Post.findById({_id: updateId}, function (err, record) {
if(!err) {
if(window.location.href.indexOf(''))
res.render('compose', {post:record});
}
});
});
and this is my compose Ejs file that I wanna do both showing and updating info with Mongodb in Ejs template:
<h1>Compose</h1>
<form action="/compose" method="post">
<div class="form-group">
<label for="posttitle"> Title</label>
<input type="text" id="" class="form-control" name="postTitle" placeholder="Title" value="<% if(window.location.href.contains("update/") > -1) { %> <%= post.title } %>" >
</div>
<div class="form-group">
<label for="desc">Description</label>
<textarea class="form-control" name="postText" id="desc" cols="30" rows="10" placeholder="Description">
<% if(window.location.href.contains("update/") > -1) { %>
<%= post.content } %>
</textarea>
</div>
<button class="btn btn-myPrimary" type="submit" value="" name="button">Publish</button>
</form>
I tried to show info from mongodb it was okay so then i made a route for updating the info using same template it gives me error

How I can get check box value and button value in this stuation? Can any one have suggest

I want to get the value of "gender" checkbox and "button" in div rect1,and react 2 to male,female and customer,shop. How I can get it?
I was try to gender == "male" or "female" but it return false
What I need change ?
function Register() {
const [username,setUsername]= useState("");
const [password,setPassword]= useState("");
const [email,setEmail]= useState("");
const [phone,setPhone]= useState("");
const [gender,setGender]= useState("");
const [role,setRole]= useState("");
const [error, setError]= useState("");
let history = useHistory();
const register = (e) => {
e.preventDefault();
axiox.post("http://localhost:5001/api/auth/register",
{username,
email,
phone,
password,
gender,
role,
}).then((response)=> {
console.log("response", response)
localStorage.setItem("login", JSON.stringify({
userLogin: true,
token: response.data.access_token,
}));
setError("");
setUsername("");
setPassword("");
setGender(");
setRole"();
history.push("/login");
}).catch(error =>setError(error.response.data.message));
};
return (
<input type="radio" name="gender" value={male} onChange={(e)=> setGender(e.target.value)}/>
<label for="male"></label>
<span>Male</span>
<input type="radio" name="gender" value={female} onChange={(e)=> setGender(e.target.value)}/>
<label for="female"></label>
<span>Female</span>
</div>
<div class="rect1">
<button class="button" type="button" value={shop} onChange={(e)=> setRole(e.target.value)}><img src={process.env.PUBLIC_URL + `/Images/shop 1.png`} /></button>
</div>
<div class="rect2">
<button class="button" type="button" value={customer} onChange={(e)=> setRole(e.target.value)}> <img src={process.env.PUBLIC_URL + `/Images/take-away.png`} /></button>
Thank for helping me
change state to boolean call it isMale
const [isMale , setIsMale]=useState(false)
than into return make
<input type="radio" name="gender" value={male} onChange={()=>
setGender(true)}/>
<label for="male"></label>
<span>Male</span>
<input type="radio" name="gender" value={female} onChange={()=> setGender(false)}/>
<label for="female"></label>
<span>Female</span>

Having Login And Register On The Same Page NodeJS

I am setting up a simple blog site and am having problems making the user authentication setup section. What I want to be happening is to have both the Register form and the Login form on the same page (for style reasons) but my issue is is that, to my knowledge, you cannot have two POST methods on one page. I have tried multiple work arounds, like using PUT or checking if the fields are empty, but these all feel hacky and don't really work. Is there anyway to have two fully functional forms on the same page that both respond to the same route? This is my method for reference:
const express = require('express')
const bcrypt = require('bcrypt');
const passport = require('passport');
const router = express.Router()
const app = express()
const User = require('../models/User')
router.get('/', async (req, res) => {
res.render('pages/account', {
pageQuery: "Account"
});
// const allUsers = await User.find({})
// console.log(allUsers)
// User.remove({}, function(err) {
// console.log('collection removed')
// });
});
router.post('/', async (req, res) => {
let name = req.body.userNameSignUp
let password = req.body.userPasswordSignUp
let passwordConfirm = req.body.userPasswordSignUpConfirm
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
userName: name,
userPassword: hashedPassword
});
if (!name || !password) {
res.render('pages/account', {
errorMessage: "*Please fill out all the fields",
pageQuery: "Account"
});
} else if (password !== passwordConfirm) {
res.render('pages/account', {
errorMessage: "*Passwords do not match",
pageQuery: "Account"
});
} else {
User.findOne({ userName: name })
.then(user => {
if (user) {
res.render('pages/account', {
errorMessage: "*Username Is Already In Use",
pageQuery: "Account"
});
}
})
}
try {
await newUser.save()
res.redirect('/account')
} catch (e) {
res.render('pages/account', {
errorMessage: "*Welp... The server's down. Come back later",
pageQuery: "Account"
});
}
});
module.exports = router;
and my ejs view for the forms:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cheese | Account</title>
<%- include('../partials/linkandsrc'); %>
<script src="js/signUpToggle.js" defer></script>
</head>
<body>
<%- include('../partials/header'); %>
<%- include('../partials/navigation'); %>
<section class="signInSec">
<div class="account-container">
<div class="user signInBx">
<div class="imgBx">
<img src="images/SignUp.jpg" alt="">
</div>
<div class="formBx">
<form action="/account" method="POST">
<h2>Sign Up</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameSignUp" placeholder="Username">
<input type="text" name="userPasswordSignUp" placeholder="Password">
<input type="text" name="userPasswordSignUpConfirm" placeholder="Confirm Password">
<input type="submit" value="Create Account">
<p class="signin">Already have an account ? Sign In.</p>
</form>
</div>
</div>
<div class="user signUpBx">
<div class="formBx">
<form action="/account" method="POST">
<h2>Sign In</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameLogIn" placeholder="Username">
<input type="text" name="userPasswordLogIn" placeholder="Password">
<input type="submit" value="Login">
<p class="signin">Don't have an account ? Sign Up.</p>
</form>
</div>
<div class="imgBx">
<img src="images/SignIn.jpg" alt="">
</div>
</div>
</div>
</section>
</body>
</html>
If you're sure you want to have the same route (/account) handle both the sign-up and the sign-in, then one approach might be to use hidden input fields.
You could place a hidden input in the sign-up form, with name formType (call it whatever you want, this is just an example) and value signup:
<form action="/account" method="POST">
<h2>Sign Up</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameSignUp" placeholder="Username">
<input type="text" name="userPasswordSignUp" placeholder="Password">
<input type="text" name="userPasswordSignUpConfirm" placeholder="Confirm Password">
<input type="hidden" name="formType" value="signup">
<input type="submit" value="Create Account">
<p class="signin">Already have an account ? Sign In.</p>
</form>
and similarly in the sign-in form, with name formType and value signin:
<form action="/account" method="POST">
<h2>Sign In</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameLogIn" placeholder="Username">
<input type="text" name="userPasswordLogIn" placeholder="Password">
<input type="hidden" name="formType" value="signin">
<input type="submit" value="Login">
<p class="signin">Don't have an account ? Sign Up.</p>
</form>
Then, in your route handler, you could have some logic that differentiates a sign-up from a sign-in using the received formType:
router.post('/', async (req, res) => {
if ('signup' === req.body.formType) {
// Server-sided sign-up logic can go here...
} else if ('signin' === req.body.formType) {
// Server-sided sign-in logic can go here....
} else {
// Something/someone has submitted an invalid form?
}
}

I am getting a Warning: A component is changing an uncontrolled input of type text to be controlled

I building a simple todo app using the MERN stack with router and able to get it going except the edit part. I have 3 routes, the "Todos" page where i use axios to get the data from my express server route. The "Add" page for create new todo and the "Edit" page for editing and deleting. Here's my todos page where each todo has a button that takes the id as a url parameter unto the Edit page.
That little pencil/paper icon on each todo is a button link that get's the ID on click. Here's my Edit page with the data.
The warning:
Here's my Todos page i'm using a custom hook to fetch the data from express server route:
import React from 'react';
import useGetAPI from '../custom_hooks/useGetAPI';
import Todo from './todo_item/Todo';
const Todos = () =>{
const data = useGetAPI('http://localhost:4000');
return (
<div className="page">
<div className="page-header">
<h1>Todo Lists</h1>
</div>
<div className="page-content">
<ul className="todo-list">
{
data.map((todo)=><Todo todo={todo} key={todo._id}/>)
}
</ul>
</div>
</div>
);
}
export default Todos;
Here's my custom hooks for fetching data - used in Todos.
import {useState,useEffect} from 'react';
import axios from 'axios';
const useGetAPI = (url)=>{
const [data,setData] = useState([]);
useEffect(()=>{
const fetchData = async ()=>{
const response = await axios.get(url);
const data = [...response.data];
const error = response.error;
if(error)
console.log(error)
else{
console.log(data);
setData(data);
}
};
fetchData();
},[url])
return data;
}
export default useGetAPI;
Here's my Edit Page
import React,{useState, useEffect, useContext, useCallback} from 'react';
import useGetApiWithParams from '../custom_hooks/useGetApiWithParams';
import {FaTelegramPlane} from 'react-icons/fa';
import axios from 'axios';
import { matchPath } from 'react-router'
const EditTodo = (props) =>{
const todoID = props.match.params.id;
const [todo,setTodo] = useState(null);
const responseData = useGetApiWithParams('http://localhost:4000/edit',todoID);
console.log(`Todo id: ${todoID}`);
/* Set default data from database */
useEffect(()=>{
setTodo(responseData);
},[responseData,setTodo]);
const [description,setDescription] = useState('');
const [responsible,setResponsible] = useState('');
const [priority,setPriority] = useState('');
const [completed,setCompleted] = useState(false);
const handleDescription = useCallback((e)=>{
setDescription(e.target.value);
},[setDescription]);
const handleResponsible = useCallback((e)=>{
setResponsible(e.target.value);
},[setResponsible]);
const handlePriority = useCallback((e)=>{
setPriority(e.target.value);
},[setPriority]);
const handleCompleted = useCallback((e)=>{
setCompleted(!completed);
},[completed,setCompleted])
const handleSubmit = useCallback((e)=>{
e.preventDefault();
console.log('Form submitted');
console.log(`Description ${description}`);
console.log(`Description ${responsible}`);
console.log(`Description ${priority}`);
console.log(`Description ${completed}`);
const updatedTodo = {
description,
responsible,
priority,
completed: false
}
axios.put(`http://localhost/4000/edit/${props.match.params.id}`, updatedTodo)
.then(res=>console.log(res.data))
.catch(function (error) {
console.log(error);
});
},[description,responsible,priority,completed,props.match.params.id]);
return (
<div className="page">
<div className="page-header">
<h1>Edit Todo</h1>
</div>
<div className="page-content">
<form id="edit-todo-form" className="todo-form" onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="description">Description:</label>
<input id="description" type="text" className="form-control" onChange={handleDescription} value={responseData.description} />
</div>
<div className="form-group">
<label htmlFor="responsible">Responsible:</label>
<input id="responsible" type="text" className="form-control" onChange={handleResponsible} value={responseData.responsible} />
</div>
<div className="form-group">
<label htmlFor="priorities">Priorities:</label>
<div id="priorities" className="form-radios">
<label htmlFor="radio1" className="radio-label">
<input name="priorityOptions" type="radio" id="radio1" value={responseData.priority} checked={priority === 'Low'} onChange={handlePriority}/>
<span className="radiomark"></span>
<span className="radiotext">Low</span>
</label>
<label htmlFor="radio2" className="radio-label">
<input type="radio" id="radio2" value={responseData.priority} checked={priority === 'Medium'} onChange={handlePriority}/>
<span className="radiomark"></span>
<span className="radiotext">Medium</span>
</label>
<label htmlFor="radio3" className="radio-label">
<input type="radio" id="radio3" value={responseData.priority} checked={priority === 'High'} onChange={handlePriority}/>
<span className="radiomark"></span>
<span className="radiotext">High</span>
</label>
</div>
</div>
<div className="form-group">
<label htmlFor="todo_completed">Status:</label>
<div id="todo_completed">
<label htmlFor="checkcompleted" className="check-label">
<input type="checkbox" id="checkcompleted" value={responseData.completed} onChange={handleCompleted}/>
<span className="checkmark"></span>
<span className="checktext">Completed</span>
</label>
</div>
</div>
<div className="form-group">
<button type="submit" className="form-btn"><FaTelegramPlane />Save Changes</button>
</div>
</form>
</div>
</div>
);
}
export default EditTodo;
Here's my custom hook for fetching data based on the Todo ID i get from the url:
import { useState,useEffect } from 'react';
import axios from 'axios';
const useGetApiWithParams = (url,params)=>{
const [data,setData] = useState([]);
useEffect(()=>{
const fetchData = async ()=>{
const response = await axios.get(`${url}/${params}`);
const data = response.data;
const error = response.error;
if(error)
console.log(`Error: ${error}`)
else{
console.log(...data);
setData(...data);
}
};
fetchData();
},[url,params])
return data;
}
export default useGetApiWithParams;
And the url with id param from MongoDB:
How to solve this? I tried the placeholder and set it's value to the response data from api but it only works for text boxes, what about the radio buttons and checkboxes? They don't seem to set the default value. For example the radio button for setting the priority value={responseData.priority} doesn't set the value as you can see here:
What i would like to happen is: from the Todos page on clicking the edit button, the edit page with a form already filled with values based on the todo id from the url parameter and be able to edit the values as well. Need help, thanks!

Use DELETE method on CRUD in SailsJS

I´m doing a CRUD app in Sails, but the delete method doesn´t works fine.
The Homepage.ejs view is a simple form:
<form action="/todo" method="post">
<input type="text" name="title">
<br><br>
<input type="text" name="description">
<br><br>
<button type="submit">Create</button>
</form>
<hr>
<ul>
<% _.each(todos, function(todo){ %>
<li style="<% if(!todo.done){ %>color: red;<% } %>"><b><%= todo.title %></b> - <%= todo.description %> </li>Detail
<form action="/todo/<%= todo.id %>" method="post">
<input type="hidden" name="_method" value="put">
<button type="submit">Completed</button>
</form>
<form action="/todo/<%= todo.id %>" method="post">
<input type="hidden" name="_method" value="delete">
<button type="submit">Delete</button>
</form>
<% }) %>
</ul>
`
The ToDoController of DELETE and findOne methods:
delete:function(req, res){
ToDo.destroy(req.param('id')).exec(function(err, todo){
if(err) return res.serverError();
return res.redirect('/');
});
},
findOne: function(req, res){
ToDo.find(req.param('id')).exec(function(err, todos){
if(err) return res.serverError();
return res.view('details', { id: req.param('id'), title: req.param('title'), description:req.param('description')});
});
}
The routes:
'/': 'ToDoController.index',
'POST /todo' : 'ToDoController.create',
'PUT /todo/:id': 'ToDoController.update',
'DELETE /todo/:id' : 'ToDoController.delete',
'GET /detail/:id': 'ToDoController.findOne'
And the details.ejs view:
<h1> ID task: <%= id %> </h1>
<h3>Title: <%= title %></h3>
<p> Task: <%= description %></p>
Any idea??
Try using your console to debug your application
delete:function(req, res){
console.log(req.param('id'));
ToDo.destroy(req.param('id')).exec(function(err, todo){
console.log(todo);
if(err) return res.serverError();
return res.redirect('/');
});
}
If you still have trouble, you should report what your console is outputting.

Resources