I use 'express' nodejs and using this code to send url into text
<form method="GET" action='/download' class="my-5">
<div class="form-group">
<label for="exampleInputEmail1"
>Link:</label
>
<input
type="text"
class="form-control"
placeholder="Enter URL"
name="url"
/>
</div>
<button type="submit" class="btn btn-primary">Download</button>
</form>
in my project I receive
const express = require("express");
const app = express();
app.set('view engine', 'ejs');
app.get("/", (req, res) => {
return res.render("index");
});
app.get("/download", async(req, res) => {
console.log(req.query.url);
});
app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});
as you can see I use get '/download' to receive url from input and doing some analazing to output new url
my quation is : how can I set this new url to an arttibute 'src' for element (such as img) in homepage without loading new page?
I need only put this new url to be value in 'src' for img in index.eje
app.get("/", (req, res) => {
return res.render("index",
{
srcAttr: 'link to image'
}
);
});
<img src="<%= srcAttr %>">
Related
Check My Node.js code Please I want to Save Contact page data in mongoose compass this don't throw any error but also not saving data
<form action="/" class="contact_form grid" method="POST">
HTML IS TOTALLY CORRECT WRITTEN I THINK PLEASE TELL ME WHATS WRONG IN THIS APP.JS CODE
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const bodyparser = require('body-parser')
const path = require('path');
mongoose.connect('mongodb://localhost:27017/ContactPage');
const port = 3000;
var contactSchema= new mongoose.Schema({
name:{type:String},
email:{type:String},
project:{type:String},
message:{type:String}
});
var Contact = mongoose.model('Contact', contactSchema);
module.exports = Contact;
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded({extended: true}))
app.set('view engine', 'ejs');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname, "index.html"))
});
app.post('/',(req,res)=>{
var myData = new Contact(req.body);
myData.save().then(()=>{
res.send(req.body)
}).catch(()=>{
res.status(400).send(req.body);
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Check My Node.js code Please I want to Save Contact page data in mongoose compass this don't throw any error but also not saving data
<form action="/" class="contact_form grid" method="POST">
<div class="contact_inputs grid">
<div class="contact_content">
<label for="" class="contact_label">Name</label>
<input type="text" name= "name" class="contact_input">
</div>
<div class="contact_content">
<label for="" class="contact_label">Email</label>
<input type="email"name="email" class="contact_input">
</div>
</div>
<div class="contact_content">
<label for="" class="contact_label">Project</label>
<input type="text" name="project" class="contact_input">
</div>
<div class="contact_content">
<label for="" class="contact_label">Message</label>
<textarea name="" id="" cols="0" rows="7" name = "message" class="contact_input"></textarea>
</div>
<div>
<a href="" class="button button--flex">
Send Message
<i class="fas fa-paper-plane button_icon"></i>
</a>
</div>
</form>
#1 you are not submitting from HTML, so instead of:
<div>
<a href="" class="button button--flex">
Send Message
<i class="fas fa-paper-plane button_icon"></i>
</a>
</div>
write:
<button type="submit">
Send Message
</button>
#2 express improvements
contactSchema file:
const mongoose = require('mongoose')
var contactSchema = new mongoose.Schema({
name: { type: String },
email: { type: String },
project: { type: String },
message: { type: String }
});
module.exports = mongoose.model('Contact', contactSchema);
app file:
const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser')
const path = require('path');
const port = 3000;
const app = express();
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, "index.html"))
});
app.post('/', (req, res) => {
var { name, email, project, message } = req.body;
var myData = new Contact({
name,
email,
project,
message,
});
myData.save().then((newData) => {
res.send(newData)
}).catch((err) => {
res.status(400).send("Error: ", err, " , Data: ", req.body);
});
});
app.listen(port, () => {
mongoose.connect('mongodb://localhost:27017/ContactPage')
.then(() => console.log("Server & DB listening at http://localhost:${port}"))
.catch(err => console.log(err));
})
im currently trying to save some data from Bootstrap input fields into my mongoDB database but i always get the error insertMovie:1 POST http://localhost:3000/insertMovie 404 (Not Found). I tried to change the Routes but i cant find my mistake. My Schema is in a file called movie.js.
I Feel like i dont really get the Route thing of express, im very new at this.
<div class="container">
<div class="row">
<div class="col">
<form method="post" action="/insertMovie">
<h1 class="text-center pt-5">Neuen Film anlegen</h1>
<div class="form-group">
<label>Titel</label>
<input
type="text"
class="form-control"
placeholder="Titel eingeben"
name="title"
/>
</div>
<div class="form-group">
<label>Beschreibung</label>
<input
type="text"
class="form-control"
placeholder="Beschreibung eingeben"
name="description"
/>
</div>
<div class="form-group">
<label>Startdatum</label>
<input
type="text"
class="form-control"
placeholder="Startdatum eingeben"
name="start"
/>
</div>
<div class="form-group">
<label>Aktuell laufend</label>
<input
type="text"
class="form-control"
placeholder="Beschreibung eingeben"
name="currentlyRunning"
/>
</div>
<input id="submit" type="submit" class="btn btn-primary" />
</form>
</div>
</div>
</div>
movies.js
const express = require("express");
const router = express.Router();
const Movie = require("../models/movie");
router.get("/", async (req, res) => {
try {
const movies = await Movie.find();
res.json(movies);
} catch (err) {
res.json({ message: err });
}
});
router.post("/insertMovie", async (req, res) => {
const movie = new Movie({
title: req.body.title,
description: req.body.description,
start: req.body.start
});
try {
const savedMovie = await movie.save();
res.json(savedMovie);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
app.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
//Middlewares
app.use(bodyParser.json());
app.use(cors());
//Import Routes
const moviesRoute = require("./routes/movies");
app.use("/movies", moviesRoute);
// include a static file serving middleware
app.use(express.static(__dirname + "/"));
// Get all Data
app.get("/data", function(req, res) {
res.sendfile("index.html");
});
// Insert new Movie
app.get("/insertMovie", function(req, res) {
res.sendfile(__dirname + "/insert.html");
});
mongoose.connect("mongodb://localhost:27017/testDB", { useNewUrlParser: true });
app.listen(3000);
The issue here is with your movie routes. With the way you set it up, your endpoint is actually:
localhost:3000/movies/insertMovie
but you are using:
localhost:3000/insertMovie
I want to save the data submitted by the user through a form using post method and then redirect it to another html page that I have on my local machine, is there any way to achieve this using Node.js or express how do I do that?
Here is the html code for form:
<html>
<head></head>
<body>
<form action="post_register.html" method="POST">
university name:<input type="text" name="name" placeholder="University name"><br>
faculty Username:<input type="text" name="facul" placeholder="faculty username"><br>
password:<input type="password" name="password" placeholder="password"><br>
<button >register</button>
</form>
</body>
and here is the javascript file:
var express = require("express");
var app = express();
var bodyparser=require("body-parser");
app.use(bodyparser.urlencoded({ extended: true }));
app.listen(3000);
app.get("/domain_register",function(req,res)
{
res.sendFile(__dirname+"/domain_register.html");
})
app.post("/post_register",function(req,res)
{
console.log(req.body);
res.end("yes");
});
all I want is that after pressing submit button the data is received and the user is redirected to post_register.html file.
I tested below code in my computer and it worked. I added res.redirect('/success') line to the post request handler and created an handler for /success path:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
You can change /success path with your naming choice.
App.js
var express = require('express')
var app = express()
var bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({ extended: true }))
app.listen(3000)
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/success', function (req, res) {
res.sendFile(__dirname + '/success.html')
})
app.post('/register', function (req, res) {
console.log(req.body)
res.redirect('/success')
})
index.html
<html>
<head></head>
<body>
<form method="post" action="/register">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
success.html
<html>
<head></head>
<body>
<h1>Welcome</h1>
</body>
</html>
I have a file server.js that looks like so:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Bear = require('./models/bear');
mongoose.connect('mongodb://123:pass123#ds1383.mlab.com:53/bears');
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
var port = 8080;
var router = express.Router();
router.use(function(req, res, next){
//console.log("Working....");
next();
});
router.get('/', function (req, res){
res.json({ message: "API Works!"});
});
router.route('/bears')
.post(function(req, res) {
console.log("hi");
var bear = new Bear(req.body); // create a new instance of the Bear model
console.log(bear);
// save the bear and check for errors
bear.save(function(err) {
if (err)
return res.send(err);
res.json({ message: 'Bear created!' });
});
});
app.use("/", (req, res) =>{
res.sendFile(__dirname + "/index.html");
});
app.use('/books', router);
app.listen(port);
console.log("Listening on port "+ port);
And my Index.html file looks like so:
<head>
</head>
<body>
<form method="POST" action="/bears">
Enter Book to add
<input type="text" id="book_name"/>
<br /><br />
Enter Quantity
<input type="number" id="book_quantity"/>
<br /><br />
Enter Price
<input type="text" id="book_price"/>
<br /><br />
<button type="submit"> Add Book </button>
</form>
</body>
I was wondering why it doesn't enter the
router.route('/bears')
.post(function(req, res){});
when clicking the "Add Book" button even thought I've set the
action="/bears" attribute.
When testing with curl, it works fine, just not with this html form
I test with curl like so:
curl -i -X POST -H "Content-Type: application/json" -d '{ "book_name" : "Android", "book_quantity": 2,"book_price": 580 }' localhost:8080/books
I'm new to Javascript so any help would be appreciated!
For post call through html form, "name" attributes for all input tags are mandatory
<form method="POST" action="/books/bears">
Enter Book to add
<input type="text" id="book_name" name="book_name"/>
<br /><br />
Enter Quantity
<input type="number" id="book_quantity" name="book_quantity"/>
<br /><br />
Enter Price
<input type="text" id="book_price" name="book_price"/>
<br /><br />
<button type="submit"> Add Book </button>
</form>
Also use
app.use(bodyParser.urlencoded({ extended: true }));
in server code
This is because form sends post data in application/x-www-form-urlencoded format, so access as req.body.book_name in server.
if json format is needed then use javascript on client and make json and then send.
app.use("/", (req, res) =>{
res.sendFile(__dirname + "/index.html");
});
Is being used for all the requests and not just '/. Instead useapp.get()` to handle the index.html page. This should then let your requests go through.
app.get("/", (req, res) =>{
res.sendFile(__dirname + "/index.html");
});
And the endpoint would be /books/bears and not just /bears since your route use is app.use('/books',router) so your endpoints would need to start with /books
<form method="POST" action="/books/bears">
A very simple page... server.js
var path = require("path");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.listen(8000, function() {
console.log("listening on port 8000");
})
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, "./static")));
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index');
})
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/basic_mongoose');
var QuoteSchema = new mongoose.Schema({
name: String,
quote: String
})
var Quote = mongoose.model('Quote', QuoteSchema);
app.post('/quotes', function(req, res) {
console.log("POST DATA", req.body);
var quote = new Quote({name: req.body.name, quote: req.body.quote});
quote.save(function(err) {
if(err) {
console.log('something went wrong');
} else {
console.log('successfully added a quote!');
res.redirect('/main');
}
})
})
index.ejs
<html>
<head>
<title></title>
</head>
<body>
<div id='container'>
<h2>Welcome to Quoting Dojo</h2>
<form action='/quotes' method='post'>
<p>Your Name: <input type = 'text' id ='name'/><p>
<p>Your Quote: <input type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>
<button id='skip'>Skip to </button>
</div>
</body>
</html>
I get "cannot /POST" when I click the submit button. Anyone?
Server loads, html page in chrome shows up. I fill in the boxes and click "add". I get the route http://localhost:8000/quotes and the error Cannot POST /quotes. Not sure what I did as I have action='post' to /quotes and app.post in the server. I don't know if I have any other issues. Thanks.
Use the name attribute instead of id, name is sent to the server, id is not.
HTML input - name vs. id
<form action='/quotes' method='post'>
<p>Your Name: <input name='name' type = 'text' id ='name'/><p>
<p>Your Quote: <input name='quote' type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>