I am currently learning node.js
And I have a question about PUT request
I can create the object
And see it in the URL
But I do not know how to write a request to edit it
For example change the price of the vehicle?
I would love to know how to write the edit request
this my HTML code
<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>Add car to the storege</h1>
<form action="/addCar" method="post">
<label for="">Car model</label>
<input name="car_model" type="text">
<label for="">Color</label>
<input name="color" type="text">
<label for="">Engine capacity</label>
<input name='Engine' type="number">
<label for="">Price</label>
<input name='price' type="number">
<label for="">id</label>
<input name='id' type="number">
<input type="submit" value="Send">
</form>
</body>
</html>
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3002
const Joi = require('#hapi/joi');
app.use(bodyParser.urlencoded({ extended: true }))
let carStorege = []
app.post('/addCar', (req,res) => {
const schema = Joi.object({
car_model: Joi.string().required(),
color: Joi.string().required(),
Engine: Joi.number().required(),
id: Joi.number().required(),
price: Joi.number().required()
})
const validation = schema.validate(req.body)
if(validation.error){
res.send('something worng!')
}
carStorege.push(req.body)
console.log(req.body)
res.send('<h1>Upload success !</h1>')
})
app.get('/', (req, res) => {
res.sendFile(__dirname+'/addCar.html')
})
app.get('/carStorege', (req, res)=> {
res.send(carStorege)
res.sendFile(__dirname+'/carStorge.html')
})
// put requset to edit the object..
app.listen(port, () => console.log('srever is live'))
send a PUT request with experss.js
use methodOverride and <input type="hidden" name="_method" value="PUT" />
<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>Add car to the storege</h1>
<form action="/addCar" method="post">
<input type="hidden" name="_method" value="PUT" />
<label for="">Car model</label>
<input name="car_model" type="text">
<label for="">Color</label>
<input name="color" type="text">
<label for="">Engine capacity</label>
<input name='Engine' type="number">
<label for="">Price</label>
<input name='price' type="number">
<label for="">id</label>
<input name='id' type="number">
<input type="submit" value="Send">
</form>
</body>
</html>
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3002
const Joi = require('#hapi/joi');
var methodOverride = require('method-override')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(methodOverride(function (req, res) {
console.log(req.body);
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
console.log('sss');
var method = req.body._method
delete req.body._method
return method
}
}))
let carStorege = []
app.post('/addCar', (req, res) => {
const schema = Joi.object({
car_model: Joi.string().required(),
color: Joi.string().required(),
Engine: Joi.number().required(),
id: Joi.number().required(),
price: Joi.number().required()
})
const validation = schema.validate(req.body)
if (validation.error) {
res.send('something worng!')
}
carStorege.push(req.body)
console.log(req.body)
res.send('<h1>Upload success !</h1>')
})
app.get('/', (req, res) => {
res.sendFile(__dirname + '/addCar.html')
})
app.get('/carStorege', (req, res) => {
res.send(carStorege)
res.sendFile(__dirname + '/carStorge.html')
})
app.put('/addCar', function (req, res) {
var car = req.car;
console.log(req.car)
res.send('<h1>sss success !</h1>')
//do update
});
app.listen(port, () => console.log('srever is live'))
Related
I build a simple express js calculator and I want the calculate to show the answer on the same page with the text boxes where I enter the numbers, now after I click calc I move to a blank page with the answer, instead I want a section under the calc button which show "Answer: XXX"
app.js
const express= require("express");
const bodyParser=require("body-parser");
const app= express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"))
app.get("/",function(req,res){
res.render('home');
});
app.get("/add",function(req,res){
res.render('add');
});
app.post("/add",function(req,res){
var num1=Number(req.body.n1);
var num2=Number(req.body.n2);
var result=num1+num2;
res.send("Answer: "+result);
});
add.ejs
<!DOCTYPE html>
<html dir="rtl">
<head>
<title>calc add</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<form action="/add" method ="post">
<input type="text" class="input" name="n1" placeholder="enter x1"><br>
<br>
<input type="text" class="input" name="n2" placeholder="enter x2"><br>
<br>
<button type="submit" class="submit" name="Submit">calc!</button>
</form>
<br>
<a class="back" href="/">home</a>
</body>
</html>
You can use fetch to make the POST request and get the answer.
<p id="result"></p>
<script>
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
fetch(this.action, {method: this.method, body: new FormData(this)})
.then(res => res.text()).then(ans => {
document.getElementById("result").textContent = ans;
});
});
</script>
I am trying to upload file from my local computer to localhost directory using multer and then send this file details along with some other form datas to mongodb.
When i am creating a post request using Thunder extension in VS Code, everything works fine. But when i use the index.html for doing the same, only file get uploaded in the localhost, but the details are not sent to mongodb and even no error occurs. So i am stuck why uploading file using frontend is not working.
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" />
<link rel="stylesheet" href="style.css" />
<title>File Upload</title>
</head>
<body>
<div class="container">
<h1>File Upload</h1>
<form
id="form"
enctype="multipart/form-data"
action="/upload"
method="post"
>
<div class="input-group">
<label for="clothid">Cloth id</label>
<input name="clothid" id="clothid" placeholder="Enter cloth id" />
</div>
<div class="input-group">
<label for="swidth">Shoulder width</label>
<input name="swidth" id="swidth" placeholder="Enter shoulder width" />
</div>
<div class="input-group">
<label for="sleeveLength">Sleeve Length</label>
<input
name="sleeveLength"
id="sleeveLength"
placeholder="Enter cloth id"
/>
</div>
<div class="input-group">
<label for="frontLength">Front Length</label>
<input
name="frontLength"
id="frontLength"
placeholder="Enter cloth id"
/>
</div>
<div class="input-group">
<label for="file">Select file</label>
<input id="file" type="file" />
</div>
<button class="submit-btn" type="submit">Upload</button>
</form>
</div>
<script src="./script.js"></script>
</body>
</html>
Script.js
const form = document.getElementById("form");
async function submitForm(e) {
e.preventDefault();
const clothid = document.getElementById("clothid");
const swidth = document.getElementById("swidth");
const sleeveLength = document.getElementById("sleeveLength");
const frontLength = document.getElementById("frontLength");
const file = document.getElementById("file");
const formData = new FormData();
formData.append("clothid", clothid.value);
formData.append("swidth", Number(swidth.value));
formData.append("sleeveLength", Number(sleeveLength.value));
formData.append("frontLength", Number(frontLength.value));
formData.append("file", file.files[0]);
// console.log(formData.getAll("file"));
const response = await fetch("http://localhost:9000/upload", {
method: "POST",
body: formData,
});
const result = await response.json();
console.log(result);
}
form.addEventListener("submit", submitForm);
Index.js
import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import Cloth from "./modals/cloth.js";
import upload from "./helper/helper.js";
import cors from "cors";
const app = express();
dotenv.config();
mongoose.set("strictQuery", true);
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
const connect = async () => {
try {
await mongoose.connect(process.env.MONGO);
console.log("Connected to Database");
} catch (error) {
throw error;
}
};
mongoose.connection.on("disconnected", () => {
console.log("mongoDB disconnected!");
});
app.post("/upload", upload.single("file"), async (req, res) => {
console.log(req.body);
try {
const file = new Cloth({
fileName: req.file.originalname,
model_link: req.file.path,
fileType: req.file.mimetype,
cloth_id: req.body.cloth_id,
accross_shoulder: req.body.accross_shoulder,
sleeve_length: req.body.sleeve_length,
front_length: req.body.front_length,
});
await file.save();
res.status(201).send("File Uploaded Successfully");
} catch (error) {
res.status(400).send(error);
}
});
const Port = 9000;
app.listen(Port, () => {
connect();
console.log(`Listening to port ${Port}`);
});
Note that the above things work when using Postman or Thunder but not using index.html file.
This is my JS, and it looks like it doesn't want to send me back to the addProduct.html page with the updated products.
document.addEventListener("DOMContentLoaded", () => {
const urlParams = new URLSearchParams(window.location.search);
const idLoaded = urlParams.get("id");
const productLoaded = urlParams.get("product");
document.getElementById("product").value = productLoaded;
const priceLoaded = urlParams.get("price");
document.getElementById("price").value = priceLoaded;
const categoryLoaded = urlParams.get("category");
document.getElementById("category").value = categoryLoaded;
document.getElementById("update").addEventListener("submit", (event) => {
event.preventDefault();
const product = document.getElementById("product").value;
const price = document.getElementById("price").value;
const category = document.getElementById("category").value;
// slet nedenstående
const params = new URL(location.href).searchParams;
const urlId = params.get("id");
const urlProduct = params.get("product");
const urlPrice = params.get("price");
// slet nedenstående
id.value = urlId
product.value = urlProduct
price.value = urlPrice
document.getElementById("update-products").addEventListener("submit", (event) => {
event.preventDefault();
//slet nedenstående
// const currentProduct = product.value
// const currentPrice = price.value
const payload = {
id: idLoaded,
product: product,
price: price,
category: category
};
/*
const payload = {
"id": urlId,
"product": currentProduct,
"price": currentPrice
}
*/
fetch("http://localhost:5005/products/update", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload),
})
//.then((response) => response.json())
.then((response) => {
if (response) {
window.alert("Congrats!")
location.href = "/addProduct.html";
}
})
.catch(() => {
window.alert("Error.")
});
});
});
});
<!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>Opdater varer detaljer</title>
<script src="updateProduct.js"></script>
</head>
<body>
<!-- ændr til update-->
<form id="update-products">
Product: <input type="text" name="product" id="product" value=""><br> Price: <input type="text" name="price" id="price" value="">
<br>
<br>
<input type="submit">
</form>
</body>
</html>
This is my product html, which shows added products as well as the updated products, which dosen't work:
I have a json file that is connected to all the products.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="addProduct.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<title> addProduct</title>
<div class="main">
<h1>Opret en vare</h1>
<p class="addProduct">Tilføj en vare ved at udfylde felterne</p>
<form id="products">
<input class="product" placeholder="Vare" id="product">
<input class="price" placeholder="Pris" id="price">
<select name="category" id="category">
<option value="Borde">Borde</option>
<option value="Stole">Stole</option>
<option value="Kopper">Kopper</option>
<option value="Kander">Kander</option>
</select>
<input class="picture" id="picture" type="file" accept="image/*">
<br><br>
<input type="submit" value="Tilføj">
</form>
<p>Vil du fjerne din vare?</p>
<form id="delete">
<input value="Slet vare" type="submit">
</form>
<br>
<table id="varer">
<tr>
<th>Produkt</th>
<th>Pris</th>
<th>Kategori</th>
<th>Billede</th>
<th>Handlinger</th>
</tr>
</table>
Hjem
<form id="delete">
<input value="Delete" type="submit" />
</form>
</body>
</html>
Remove
document.getElementById("update-products").addEventListener("submit", (event) => {
event.preventDefault();
and change
document.getElementById("update").addEventListener("submit", (event) => {
to
document.getElementById("update-products").addEventListener("submit", (event) => {
and add a category or remove the code that sets it
Remove
// slet nedenstående
id.value = urlId
product.value = urlProduct
price.value = urlPrice
and change to
const payload = {
id: idLoaded,
product: product,
price: price,
category: category
};
lastly you need to change the URL handling - see the code I added
Also I prefer
window.addEventListener("load", () => {
to DOMContentLoaded
Like this
window.addEventListener("load", () => {
// remove the line under
const url = new URL("https://minside.dk/search?id=999&product=krus&category=kopper&price=25.99") // new URL(window.location.href);
// remove comments
// const url = new URL(window.location.href);
const urlParams = url.searchParams;
const idLoaded = urlParams.get("id");
const productLoaded = urlParams.get("product");
const priceLoaded = urlParams.get("price");
const categoryLoaded = urlParams.get("category");
document.getElementById("category").value = categoryLoaded;
document.getElementById("price").value = priceLoaded;
document.getElementById("product").value = productLoaded;
document.getElementById("update-products").addEventListener("submit", (event) => {
event.preventDefault();
const product = document.getElementById("product").value;
const price = document.getElementById("price").value; // should not actually be allowed to be changed?
const category = document.getElementById("category").value;
urlParams.set("product", product);
urlParams.set("price", price);
urlParams.set("category", category); // should not really change, should it?
const payload = {
id: idLoaded,
product: product,
price: price,
category: category
};
fetch("http://localhost:5005/products/update", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload),
})
//.then((response) => response.json())
.then((response) => {
if (response) {
window.alert("Congrats!")
location.href = url.toString();
}
})
.catch(() => {
window.alert("Error.")
});
});
});
<!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>Opdater varer detaljer</title>
<script src="updateProduct.js"></script>
</head>
<body>
<!-- ændr til update-->
<form id="update-products">
Product: <input type="text" name="product" id="product" value="" /><br/> Price: <input type="text" name="price" id="price" value="" /> Category: <input type="text" name="category" id="category" value="" />
<br>
<br>
<input type="submit">
</form>
</body>
</html>
So I've been trying to get the data from my form and input it into my database for ages and it just isn't working. There are no errors and nothing is logging.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="UTF-8">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Signup for NGOs</title>
</head>
<body>
<form class="mt-4 mr-4 ml-4" id="form" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name of NGO">
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Address">
</div>
<div class="form-group">
<label for="phone">Contact Information</label>
<input type="number" class="form-control" id="phone" placeholder="Contact Number">
</div>
<div class="form-group">
<label for="requirements">Requirements (Seperate by Commas)</label>
<input type="text" class="form-control" id="requirements" placeholder="Requirements">
</div>
<button type="submit" class="btn btn-primary" id="submitButton">Submit</button>
</form>
<!-- Optional JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="signup.js"></script>
</body>
</html>
And this is my Node.js code:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
// I've replaced my original username and password with placeholders
var uri = "mongodb+srv://username:password#helpbook-rlpsi.gcp.mongodb.net/test?retryWrites=true";
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
app.post('/signup', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
dbConn.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
});
I don't know what's going wrong. My data isn't being uploaded to the database and for some reason none of the console.log() statements are being executed.
The promise probably resolves before the signup handler is called.
Try the following:
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
dbConn.then(function(client) {
app.post('/signup', function (req, res) {
delete req.body._id; // for safety reasons
client.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
})
.catch(function(err){
console.log(err)
});
Looking at your question specifically, you are not using any action in your form.
<form class="mt-4 mr-4 ml-4" id="form" method="post" action="/signup">
...
</form>
So it is not getting posted to your route. (That's why I specifically asked if console logging before the dbconn is working or not)
I'm trying to build an app that lets me enter in information about an event and then have that pinned on a map. I'm stuck at the beginning though on actually saving the information. When I use Inspect in Chrome, it tells me it posted, but the data is blank. I'm pretty new to this kind of stuff and not sure where I'm going wrong.
The first file is the app.js where I set up the database, a simple partial schema, etc.
The second file is my dashboard.html that displays the map and the form. I was trying the onsubmit/javascript stuff which displays the data without refreshing the page, but ideally I want to be able to refresh the page and have the data still be posted somewhere.
Any help would be greatly appreciated! Thanks! :)
require('dotenv').config({ silent: false }); // Retrieve .env contents
var http = require('http'); // Basic HTTP functionality
var path = require('path'); // Parse directory paths
var express = require('express'); // Provide static routing to pages
var app = express();
var Router = require('router')
var router = Router()
var server = http.Server(app);
var port = 8080;
var app = setupExpress();
// Import mongoose module and connect the database
var mongoose = require('mongoose');
var mongoDB = 'mongodb://Username:Password#ds159180.mlab.com:59180/app-database';
mongoose.connect(mongoDB);
//Get the default connection
var db = mongoose.connection;
// Start server on port 8080
// localhost:8080
server.listen(port);
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//Define a schema
var Schema = mongoose.Schema;
var EventSchema = new Schema({
eventName : String,
eventType : String
});
var Event = mongoose.model('Event', EventSchema);
app.post('/dashboard', function(req, res) {
res.json(req.body); // req.body is your form data
});
app.post('/dashboard', function(req,res){
var content = new Event({
eventName : req.body.eventName,
eventType : req.body.eventType
}).save(function(err,doc){
if(err){
return handleError(err);
} else {
console.log('your form has been saved');
}
})
});
function setupExpress()
{
// Set default path for views and public
var viewsDir = path.join(__dirname, 'views');
var publicDir = path.join(__dirname, 'public');
app.use(express.static(publicDir));
// Root page is login form
app.get('/', function(req, res)
{
res.sendFile('views/index.html', { root: '.' });
});
// Once logged in, home page is dashboard
app.get('/dashboard', function(req, res)
{
res.sendFile('views/dashboard.html', { root: '.' });
});
// Redirect to error page if there's an issue
app.use(function(err, req, res, next)
{
console.log(err.stack);
res.status(err.status || 500);
res.sendFile('/views/error.html', { root: '.' });
});
return app;
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Web browser tab title -->
<title>App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="http://www.your-domain.com/easy-comment/jquery.easy-comment.min.js"></script>
<title>App Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-8" style="margin-top: 30px">
<div class="panel panel-default">
<div class="panel-heading text-center">
<i class="fa fa-map-marker fa-3x"> Add Event</i>
</div>
<div class="panel-body">
<div class="col-lg-6">
<form id="eventForm" method="post" onsubmit="return false">
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" class="form-control" id="eventName" placeholder="Event name">
</div>
<div class="form-group">
<label for="eventType">Type</label>
<select class="form-control" id="eventType">
<option>Study Group</option>
<option>Food</option>
<option>Meeting</option>
<option>Danger</option>
</select>
</div>
<div class="form-group">
<label for="eventLocation">Location</label>
<select class="form-control" id="eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label for="eventNotes">Event Notes</label>
<textarea class="form-control" id="eventNotes" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div id="confirm"><div>
<script type="text/javascript">
var txt = document.getElementById("eventName");
document.getElementById("eventForm").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var eventName = txt.value;
document.getElementById("confirm").innerHTML += '<p>Name: ' + eventName + '</p>';
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
You should use body-parser to change your data post from client to json
var bodyParser = require('body-parser')
app.use(bodyParser.json())
You can get json data via req.body