my index.js file and views/products/edit.ejs files :
const express = require('express')
const path = require('path')
const mongoose = require('mongoose');
const methodOverride = require('method-override')
const app = express()
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, "views"))
app.use(express.urlencoded({
extended: true
}))
app.use(methodOverride('_method'))
mongoose.connect('mongodb://localhost:27017/farmStand')
.then((data) => {
console.log("successfully connected to database")
console.log(data)
}).catch(error => {
console.log("error occured")
console.log(error)
})
function wrapperASync(fn) {
return function(req, resp, next) {
fn(req, resp, next).catch((e) => {
next(e)
})
}
}
let categories = ['fruits', 'vegetables', 'dairy']
const Product = require('./models/product');
const {
param
} = require('express/lib/request');
app.get('/', (req, resp) => {
resp.send("getting data")
})
app.get('/products', async(req, resp) => {
const {
category
} = req.query
const selectedcategory = category
console.log(selectedcategory)
if (selectedcategory) {
let products = await Product.find({
category: selectedcategory
})
resp.render("products/index", {
products,
selectedcategory
})
} else {
let products = await Product.find({})
// console.log("found products")
resp.render("products/index", {
products,
selectedcategory: "All"
})
}
})
app.get('/products/:id', async(req, resp, next) => {
const {
id
} = req.params
let myproduct = await Product.findById(id)
if (!myproduct) {
return next(new AppError("product not found", 404))
}
// console.log(myproduct)
resp.render('products/details', {
myproduct
})
})
app.get('/product/new', (req, resp) => {
resp.render('products/new', {
categories
})
})
app.get('/products/:id/edit', wrapperASync(async(req, resp, next) => {
const {
id
} = req.params
const product = await Product.findById(id)
if (!product) {
throw new AppError("product not found", 404)
}
resp.render('products/edit', {
product,
categories
})
}))
app.put('/products/:id', wrapperASync(async(req, resp, next) => {
const {
id
} = req.params
const updatedValues = req.body
const newvalue = await Product.findByIdAndUpdate(id, updatedValues, {
runValidators: true,
new: true
})
// console.log(newvalue)
resp.redirect(`/products/${newvalue._id}`)
}))
app.post('/products', wrapperASync(async(req, resp) => {
const newdoc = req.body
const myproduct = new Product(newdoc)
console.log(myproduct)
await myproduct.save()
resp.redirect(`/products/${myproduct._id}`)
}))
app.delete('/products/:id', async(req, resp, next) => {
try {
const {
id
} = req.params
const deleted_product = await Product.findOneAndDelete(id)
resp.redirect('/products')
} catch (error) {
next(error)
}
})
app.use((err, req, resp, next) => {
console.log(err.name)
next(err)
})
app.use((err, req, resp, next) => {
const {
status = 404, message = "something went wrong"
} = err
resp.status(status).send(message)
})
app.listen(3000, () => {
console.log("server started successfully")
})
<!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> enter product details</h1>
<form action="/products/<%= product.id %>?_method=PUT " method="POST">
<label for="name">enter the name of the product : </label>
<input type="text" name="name" id="name" placeholder="name" value="<%= product.name %> ">
<label for="price">enter the price in dollars : </label>
<input type="number" name="price" id="price" placeholder="price" value="<%= product.price %>">
<label for="category">category : </label>
<select name="category" id="category">
<% for(category of categories) { %>
<option value="<%= category %>" <%=p roduct.category===c ategory ? "selected": '' %> >
<%= category %>
</option>
<% } %>
</select>
<button>add new details</button>
</form>
<section>
exit
</section>
</body>
</html>
my models/product.js file :
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
name : {
type : String,
required : true
},
price:{
type : Number,
required : true,
min : 0
},
category:{
type:String,
lowercase :true,
enum : ["fruits","vegetables","dairy"]
}
})
const Product = new mongoose.model('Product',productSchema);
module.exports = Product;
my problem : I have installed all the dependencies my problem is when I am entering in to the edit page and then when I type my id incorrect and of different length in the url for which Iam listening for I get the CastError printed out on my console and when I keep my name Field as blank and edit then I get the ValidationError printed out on my console but after getting the validation error when I change the id of the product which is incorrect again and which is of different length in the url after getting validation error response and send the request in chrome my server gets error and breaks even though I handle the error of my /products/:id put route
please help me
Related
I have this express server and whenever you post username or password 1 or 1=1 it will not respond. there will be no console output or errors. And it will keep working after that.
I have tried adding app.post("*") at the top of the code and it won't even fire the event (so its not sql or the app.use).
If you want to test it go to https://speedcubing.top/login
index.js
const cubing = require('./cubing.js')
const mysql = require('./SQL.js')
const express = require('express')
const cookies = require('cookie-parser')
const uuid = require('uuid')
const app = express()
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cookies())
app.use(express.static('static'))
//database
const sql = new mysql('localhost', 'user', 'pass')
const systemdb = sql.database('speedcubingsystem')
//use
app.use(async (req, res, next) => {
cubing.info("use")
let redir = false
if (req.url.endsWith('/') && req.url != '/') {
redir = true
req.url = req.url.slice(0, -1)
}
if (req.subdomains[0] == 'www') {
redir = true
}
if (req.url.includes('?')) {
redir = true
req.url = req.url.split('?')[0]
}
if (redir)
res.redirect('https://speedcubing.top' + req.url)
else {
if (req.url != 'myip') {
req.loginName = ''
req.admin = false
if (req.cookies.login !== undefined) {
const result = await systemdb.query("SELECT user,admin FROM web_user WHERE token='" + req.cookies.login.token + "'")
if (result.length > 0) {
req.loginName = result[0].user
req.admin = result[0].admin.lastIndexOf(1) !== -1
}
}
}
next()
}
})
//index page
app.get('/', async (req, res) => {
res.render('index.ejs', {
loginName: req.loginName,
})
})
//login page
app.post('/login', async (req, res) => {
cubing.info("post login")
const name = mysql.validateString(req.body.username)
const pw = mysql.validateString(req.body.password)
if ((await systemdb.query('SELECT * FROM web_user WHERE user=' + name + ' AND password=' + pw)).length > 0) {
const token = uuid.v4()
systemdb.query("UPDATE web_user SET token='" + token + "' WHERE user=" + name + ' AND password=' + pw)
res.cookie('login', { token: token }, { httpOnly: false })
res.redirect('/')
} else res.render('login.ejs', {
loginName: req.loginName,
error: true,
})
})
app.get('/login', async (req, res) => {
cubing.info("get login")
if (req.loginName != '')
res.redirect('https://speedcubing.top')
else res.render('login.ejs', {
loginName: '',
error: false
})
})
//logout
app.get('/logout', async (req, res) => {
res.clearCookie('login')
res.redirect('/')
})
app.listen(25080, function () {
cubing.info('Listening on /0.0.0.0:25080')
})
login.ejs
<title>speedcubing.top</title>
<html>
<head>
<link rel="stylesheet" href="/a.css">
</head>
<body><div class="wrapper">
<%- include("./global/header.ejs") %>
<table width="200" border="0" align="center">
<tr><td>
<form action="login" method="post">
<% if(error !== undefined && error){%>
<p><%= "invalid usr/pw" %></p>
<% } %>
username: <input type="text" name="username" ><br/>
password: <input type="password" name="password" ><br/>
<input type="submit" value="login">
</form>
</td></tr>
</table>
</div>
<%- include("./global/footer.ejs") %>
</body>
</html>
I have a Red Hat Enterpise Linux 9 server hosted at a data center, which has an Apache web server and a MySQL installation. MySQL listens on 3306, and Apache on 80 (defaults).
I'm new to React and Express, and I'm testing a client-server app. I built the client side with create-react-app, and this is the code for App.js
App.js
import "./App.css";
import { useState } from "react";
import Axios from "axios";
function App() {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const [country, setCountry] = useState("");
const [position, setPosition] = useState("");
const [wage, setWage] = useState(0);
const [newWage, setNewWage] = useState(0);
const [employeeList, setEmployeeList] = useState([]);
const addEmployee = () => {
Axios.post("http://1.2.3.4:3001/create", {
name: name,
age: age,
country: country,
position: position,
wage: wage,
}).then(() => {
setEmployeeList([
...employeeList,
{
name: name,
age: age,
country: country,
position: position,
wage: wage,
},
]);
});
};
const getEmployees = () => {
Axios.get("http://1.2.3.4:3001/employees").then((response) => {
setEmployeeList(response.data);
console.log("retrieving the list");
console.log(employeeList);
});
};
getEmployees();
const updateEmployeeWage = (id) => {
Axios.put("http://1.2.3.4:3001/update", { wage: newWage, id: id }).then(
(response) => {
setEmployeeList(
employeeList.map((val) => {
return val.id == id
? {
id: val.id,
name: val.name,
country: val.country,
age: val.age,
position: val.position,
wage: newWage,
}
: val;
})
);
}
);
};
const deleteEmployee = (id) => {
Axios.delete(`http://1.2.3.4:3001/delete/${id}`).then((response) => {
setEmployeeList(
employeeList.filter((val) => {
return val.id != id;
})
);
});
};
return (
<div className="App">
<div className="information">
<label>Name:</label>
<input
type="text"
onChange={(event) => {
setName(event.target.value);
}}
/>
<label>Age:</label>
<input
type="number"
onChange={(event) => {
setAge(event.target.value);
}}
/>
<label>Country:</label>
<input
type="text"
onChange={(event) => {
setCountry(event.target.value);
}}
/>
<label>Position:</label>
<input
type="text"
onChange={(event) => {
setPosition(event.target.value);
}}
/>
<label>Wage (year):</label>
<input
type="number"
onChange={(event) => {
setWage(event.target.value);
}}
/>
<button onClick={addEmployee}>Add Employee</button>
</div>
<div className="employees">
<button onClick={getEmployees}>Show Employees</button>
{employeeList.map((val, key) => {
return (
<div className="employee">
<div>
<h3>Name: {val.name}</h3>
<h3>Age: {val.age}</h3>
<h3>Country: {val.country}</h3>
<h3>Position: {val.position}</h3>
<h3>Wage: {val.wage}</h3>
</div>
<div>
<input
type="text"
placeholder="2000..."
onChange={(event) => {
setNewWage(event.target.value);
}}
/>
<button
onClick={() => {
updateEmployeeWage(val.id);
}}
>
{" "}
Update
</button>
<button
onClick={() => {
deleteEmployee(val.id);
}}
>
Delete
</button>
</div>
</div>
);
})}
</div>
</div>
);
}
export default App;
The server is supposed to run on port 3001 of the same machine. The code for the server's index.js is below.
index.js for server
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user: "apphost",
host: "0.0.0.0",
password: "password",
database: "employeeSystem",
insecureAuth: 'true'
});
app.get('/home', (req, res) => {
res.send("HELLO THERE\n");
});
app.post("/create", (req, res) => {
const name = req.body.name;
const age = req.body.age;
const country = req.body.country;
const position = req.body.position;
const wage = req.body.wage;
db.query(
"INSERT INTO employees (name, age, country, position, wage) VALUES (?,?,?,?,?)",
[name, age, country, position, wage],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
});
app.get("/employees", (req, res) => {
db.query("SELECT * FROM employees", (err, result) => {
if (err) {
console.log('server index.js problem')
console.log(err);
} else {
res.send(result);
}
});
});
app.put("/update", (req, res) => {
const id = req.body.id;
const wage = req.body.wage;
db.query(
"UPDATE employees SET wage = ? WHERE id = ?",
[wage, id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
app.delete("/delete/:id", (req, res) => {
const id = req.params.id;
db.query("DELETE FROM employees WHERE id = ?", id, (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});
app.listen(3001, () => {
console.log("Server running on port 3001.");
});
After running the server with node index.js, when I run curl http://1.2.3.4:3001/employees from a machine on the same physical network, I get a JSON output of the data in the MySQL database as expected. From my Windows CMD, a browser on my Windows machine, or from my phone, the request times out.
Keep in mind that I'm SSH-ing to the linux VM, while on a VPN provided by the data center.
This is the error I get on chrome:
Uncaught (in promise) M {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
Not sure what the issue is. Tried a lot of solutions from all over the internet, but nothing seems to work.
If any more information is needed, feel free to ask. I'll do anything to get this issue fixed and understand what I'm doing wrong.
Thanks in advance!
I have a React.js task that requires me to make a POST request to the server. Now, I want to send a POST request when a user clicks a submit button. But I keep getting these 2 errors:
App.js:19 POST http://localhost:3001/ net::ERR_CONNECTION_RESET
App.js:19 Uncaught (in promise) TypeError: Failed to fetch at handleSubmit (App.js:19:1)
My React code:
import "./App.css";
function App() {
const [inputs, setInputs] = useState({});
const [backendData, setBackendData] = useState();
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setInputs((state) => ({ ...state, [name]: value }));
};
const handleSubmit = (e) => {
e.preventDefault();
/*when submit is clicked, we are goint to send a POST request so that data of the inputs is created*/
console.log(inputs);
fetch("http://localhost:3001/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(inputs),
});
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
name="projectTitle"
onChange={handleChange}
className="project-title"
value={inputs.projectTitle || " "}
/>
<input
type="text"
name="id"
className="id"
onChange={handleChange}
value={inputs.id || " "}
/>
<input type="submit" value="Submit" />
</form>
</div>
);
}
export default App;
My Express code:
const express = require("express");
const app = express();
const fs = require("fs");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
var obj = { projects: [] };
app.post("/", (req, res, next) => {
let identifier = req.query.identify; //id of project
fs.readFile("webProjects.json", (err, data) => {
if (err) throw err;
obj = JSON.parse(data);
obj.projects.push({
id: identifier,
title: req.query.project,
description: req.query.description,
});
let json = JSON.stringify(obj);
fs.writeFile("webProjects.json", json, (err) => {
if (err) throw err;
console.log("updatedd", req.body.inputs);
});
});
});
/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next) => {
fs.readFile("webProjects.json", (err, data) => {
console.log(data);
obj = JSON.parse(data);
// assign the filtered array back to the original array
obj.projects = obj.projects.filter((item) => {
let url = req.query.identify;
return item.id !== url;
});
console.log(obj);
let json = JSON.stringify(obj);
fs.writeFile("webProjects.json", json, (err) => {
if (err) throw err;
console.log(obj);
});
});
});
/*when user navigates to another page, we display the data of the resource*/
app.get("/api", (req, res, next) => {
fs.readFile("webProjects.json", (err, data) => {
if (err) throw err;
res.json(JSON.parse(data));
console.log("done");
});
});
/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get("*", (req, res, next) => {
let err = new Error("There was an error in accessing the page you wanted");
err.statusCode = 404;
next(err);
});
app.use((err, req, res, next) => {
console.log(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
let PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log("server has listened");
});
If the front end is created with create-react-app command, the problem might be the proxy one. In your package.json file, you can add proxy as shown below:
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:3001"
When the login button is pressed I send a POST request successfully to my app.js file and just to test try to redirect it with (as instructed) used code 302.
My get request '/' is called and logged
Exist!
did we work? Why does my sendFile not work as I expected? I am relatively new to this so I may be off base on how to do this. My goal is to after submitting a POST transition the client to a new HTML file
const express = require('express');
const { json } = require('express/lib/response');
const app = express();
const fs = require('fs');
app.use(express.json());
app.get('/Register', (req, res) => {
res.sendFile(__dirname + '/Register.html');
});
app.get('/Login', (req, res) => {
res.sendFile(__dirname + '/Login.html');
});
app.get('/RegisterComplete', (req, res) => {
res.sendFile(__dirname + '/RegisterComplete.html');
});
app.get('/', (req, res) => {
console.log('did we work?')
res.sendFile(__dirname + '/Home.html');
});
app.post('/', (req, res) => {
const { username, password } = req.body;
const { authorization } = req.headers;
res.send({
username,
password,
authorization,
});
// fs.readFile('helloworld.txt', 'utf8' , (err, data) => {
// fs.writeFile('helloworld.txt', JSON.stringify(req.body) + data, function (err) {
// if (err) return console.log(err);
// });
// })
console.log(req.body + 'i am not what we need');
});
app.post('/Register', (req, res) => {
fs.readFile('Logins.Json', 'utf8' , (err, data) => {
const obj = req.body;
const testObj = JSON.stringify(obj)
const fileContent = JSON.parse(data)
const newContent = fileContent['User Info']
let test = new Boolean(false)
for (let i = 0; i < newContent.length; i++) {
if(JSON.stringify(newContent[i]) == testObj){
//console.log('Exist!')
test = true
break
}
}
//console.log(req.body);
if (test == true) {
console.log('Exist!')
}else{
newContent.push(obj);
const newData = JSON.stringify(fileContent)
fs.writeFile('Logins.Json', newData, function (err) {
console.log('Created Account!')
if (err) return console.log(err);
})
}
if (err) return console.log(err);
})
res.end()
//console.log(req.body);
});
app.post('/Login', (req, res) => {
res.redirect(302,'/');
fs.readFile('Logins.Json', 'utf8' , (err, data) => {
const obj = req.body;
const testObj = JSON.stringify(obj)
const fileContent = JSON.parse(data)
const newContent = fileContent['User Info']
let test = new Boolean(false)
for (let i = 0; i < newContent.length; i++) {
if(JSON.stringify(newContent[i]) == testObj){
//console.log('Exist!')
test = true
break
}
}
//console.log(req.body);
if (test == true) {
console.log('Exist!')
//login successful
}else{
console.log('Failed')
// login failed
}
if (err) return console.log(err);
})
});
app.listen(7777, () => {
console.log('Our express server is up on port 1000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>eV Login</title>
</head>
<body>
<form>
<div>
<label>Username</label>
<input type="text" id="user" />
</div>
<div>
<label>Password</label>
<input type="password" id="pass" />
</div>
<button type="submit">Login</button>
</form>
<script>
document.querySelector('button')
.addEventListener('click', (e) => {
e.preventDefault();
const username = document
.querySelector('#user').value;
const password = document
.querySelector('#pass').value;
fetch('/Login', {
method: 'POST',
headers: {
Authorization: 'Vital Gaming',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username,
password,
}),
})
.then((res) => {
return res.json();
})
.then((data) => console.log(data));
});
</script>
</body>
</html>
The project is on my github:
https://github.com/vabmoni/luiztools
I followed this tutorial:
https://www.luiztools.com.br/post/tutorial-crud-em-node-js-com-driver-nativo-do-mongodb/
but when I edit the customer, I have an error 404.
To run the project:
Install MongoDB Server
Add MongoDB /bin folder to PATH
Open first CMD: mongod --dbpath C:{Your Path}\webapp\data
Open second CMD: mongo
Open third CMD: npm install and npm start
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', async (req, res, next) => {
try {
const docs = await global.db.findAll();
res.render('index', { title: 'Lista de Clientes', docs });
} catch (err) {
next(err);
}
});
router.get('/new', (req, res, next) => {
res.render('new', { title: 'Novo Cadastro', doc: { "nome": "", "idade": "" }, action: '/new' });
})
router.post('/new', async (req, res, next) => {
const nome = req.body.nome;
const idade = parseInt(req.body.idade);
try {
const result = await global.db.insert({ nome, idade });
console.log(result);
res.redirect('/');
} catch (err) {
next(err);
}
});
router.post('/edit/:id', async (req, res) => {
const id = req.params.id;
const nome = req.body.nome;
const idade = parseInt(req.body.idade);
try {
const result = await global.db.update(id, { nome, idade });
console.log(result);
res.redirect('/');
} catch (err) {
next(err);
}
});
router.get('/delete/:id', async (req, res) => {
const id = req.params.id;
try {
const result = await global.db.deleteOne(id);
console.log(result);
res.redirect('/');
} catch (err) {
next(err);
}
});
module.exports = router;
views/index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<ul>
<% docs.forEach(function(customer){ %>
<li>
<a href="/edit/<%= customer._id %>">
<%= customer.nome %>
</a>
<a href="/delete/<%= customer._id %>"
onclick="return confirm('Tem certeza que deseja excluir?');">
X
</a>
</li>
<% }) %>
</ul>
<hr />
Cadastrar novo cliente
</body>
</html>
views\new.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<form action="<%= action %>" method="POST">
<p>Nome:<input type="text" name="nome" value="<%= doc.nome %>" /></p>
<p>Idade:<input type="number" name="idade" value="<%= doc.idade %>" /></p>
<input type="submit" value="Salvar" />
</form>
</body>
</html>
db.js
const mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://localhost")
.then(conn => global.conn = conn.db("webapp"))
.catch(err => console.log(err))
function findAll() {
return global.conn.collection("customers").find().toArray();
}
function insert(customer) {
return global.conn.collection("customers").insertOne(customer);
}
const ObjectId = require("mongodb").ObjectId;
function findOne(id) {
return global.conn.collection("customers").findOne(new ObjectId(id));
}
function update(id, customer) {
return global.conn.collection("customers").updateOne({ _id: new ObjectId(id) }, { $set: customer });
}
function deleteOne(id) {
return global.conn.collection("customers").deleteOne({ _id: new ObjectId(id) });
}
module.exports = { findAll, insert, findOne, update, deleteOne }