Basic question here: I set up a local server with express and I want to create a file on the server by clicking a HTML button.
Here is the srcServer.js:
var express = require('express');
var path = require('path');
var open = require('open');
var fs = require('fs');
var port = 3000;
var app = express();
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '../src/index.html'));
});
app.post('/', function(request, respond) {
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
});
app.listen(port, function(err){
if(err){
console.log(err);
}else{
open('http://localhost:' + port);
}
});
And this is the index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h2>The Button Element</h2>
<form action="" method="post">
<button name="foo" value="send">Send</button>
</form>
</body>
</html>
I am pretty sure the problem is how I am handling the HTML button, but I dont know better. The error I receive when I click on it is: Cannot POST /.
The problem was with the folders- I messed up calling them in the srcServer.js. It works fine after I put all the files in one folder, this way it was easier to do it right.
Related
I want to upload a file using NodeJS streams and HTML forms. I have a simple server.
It is working when I upload the file using Postman. But when I upload through HTML form, the file is uploaded but is not readable. How to do it?
This is index.js:
const app = require('express')();
const fs = require('fs');
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/file-upload', (req, res) => {
const filePath = 'uploads/uploaded-file';
const stream = fs.createWriteStream(filePath);
req.pipe(stream);
stream.on('close', () => {
res.send({ status: 'success', filePath })
});
});
// Start server
app.listen(3000, () => console.log("The server is running at localhost:3000"));
This is index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h1>File Upload</h1>
<form method="post" action="/file-upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="upload">
</form>
</body>
</html>
This is the postman request screenshot:
As you can see you're trying to upload the file through a form using multipart/form-data whereas you're uploading it as binary in postman.
To fix this you can setup up a multipart/form-data parser on your server side (e.g. using multer), which would look something like this:
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
// ...
app.post('/file-upload', upload.single('file'), (req, res) => {
res.send({ status: 'success', filePath: req.file.path })
});
I am building a simple To Do application Using node js, express, mongodb and ejs.
My get Route renders the form and the post route handles post request on the form, they both work perfect, any time I insert a (todo) it gets saved and can be found in my Mongo compass.
But it does not appear on the screen as Todo App should be. It only prints out usual bullets of (ul). I don't know what I am doing wrong, here is my code:
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const session = require('express-session');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/Todo-App",
{useUnifiedTopology:true,useNewUrlParser:true,useFindAndModify:false,useCreateIndex:true});
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret:"secret"}));
var todoschema = mongoose.Schema({
item:String,
});
var Todo = mongoose.model("Todo",todoschema);
app.get('/',(req,res)=>{
res.render('home.ejs',{Todo:Todo});
});
app.post('/',(req,res)=>{
var newTodo = new Todo({
item:req.body.item,
});
newTodo.save((err,result)=>{
if(err){
throw err;
}
else{
res.redirect('/');
}
})
})
app.listen(8080,()=>{
console.log("App is running...")
})
Here is my code in the ejs file
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>My To-Do Application</h1>
<form action="/" method="post">
<input type="text" name="item" placeholder="Enter Item">
<input type="submit" value="Add To List">
</form>
<%for(var i = 0; i < Todo.length; i++){%>
<li> <%=Todo[i]%></li>
<%}%>
</body>
</html>
I think the issue is here
app.get('/', (req, res) => {
res.render('home.ejs', { Todo : Todo });
});
you are doing the res.render without finding the documents from db
I think we need to add a find query before doing res.render
it should be something like that
app.get('/', (req, res) => {
Todo.find({}, (err, todos) => { // passing an empty object as a first argument to the find method means we need to get all the documents from Todo collection
if (err) {
throw err;
} else {
res.render('home.ejs', { Todo: todos });
}
});
});
hope it helps
I have a nodejs code given with html code, I want to show a sweet alert on client side,after process a function in nodejs?.
var express = require('express');
var router = express.Router();
const Swal = require('sweetalert2');
router.post('/add', function(req, res, next) {
Swal('Hello world!');
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form action="/add" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
Here's the only way you can show a popup swal
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.json("Hello world!")
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form id="form" action="#" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
<script>
//import JQuery from script
//import swal script
$("#form").on("submit", function(e){
e.preventDefault();
$.ajax({
url: "/add",
method: "post"
}).done(d=>{
swal(e.responseJSON);
});
})
</script>
Here you can do using EJS
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.status(201).render('new', { isAdded : true } );
});
In HTML side
<% if (isAdded) { %>
<script>
Swal.fire(
'Good job!',
'Data saved',
'success'
)
</script>
<% } %>
In order to deal with this, you can use query parameters.
So, Here is what you can do
On the server
var express = require('express');
var router = express.Router();
router.post('/login', (req, res)=>{
res.redirect("/login?success=true&message=Logged In Successfully")
});
On the Client-Side (EJS)
<script>
var urlParams = new URLSearchParams(window.location.search);
if(urlParams.has('success') && urlParams.get('success')){
swal({
title: "Failed",
text: `${message}`,
icon: "error",
button: "Okay",
}).then(()=>{
console.log(window.location.hostname)
window.location.replace(window.location.origin + '/login');
})
}
This will simply popup swal. And you can toggle the value of success to render error and success messages.
Created a sample scalable application using nodejs connected with mysql database in openshift . But I got 502 error bad gateway.changed #option httpchk GET / in haproxy.
I have a database testnodejs having table users(id int,name varchar);
my sample code
index.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function () {
$.get('/users',data,function(data){
});
});
});
</script>
</head>
<body>
<h3>Enter a username</h3>
<input id="user" type="text" />
<input id="submit" type="submit" />
<p id="output"></p>
</body>
</html>
app.js
var express = require('express'),
mysql = require('mysql');
var ipaddr = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var app = module.exports = express.createServer();
var connection = mysql.createConnection({
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password :process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
port :process.env.OPENSHIFT_MYSQL_DB_PORT,
db :"testnodejs"
});
app.use(express.bodyParser());
connection.connect();
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/users', function(req, res){
connection.query("select * from users where name="+req.query["name"],
function(err, result, fields) {
if (err) throw err;
else {
res.send(result);
}
});
});
app.listen(port,ipaddr);
console.log("Express server listening on port %d in %s mode",port, ipaddr, app.settings.env);
I am trying to upload a file to my node js server using express.
Here is my nodejs code:
var express=require('express');
var app=express();
var fs=require('fs');
var sys=require('sys');
app.listen(8080);
app.get('/',function(req,res){
fs.readFile('upload.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.post('/upload',function(req,res)
{
console.log(req.files);
fs.readFile(req.files.displayImage.path, function (err, data) {
// ...
var newPath = __dirname;
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
});
My upload.html file:
<html>
<head>
<title>Upload Example</title>
</head>
<body>
<form id="uploadForm"
enctype="multipart/form-data"
action="/upload"
method="post">
<input type="file" id="userPhotoInput" name="displayImage" />
<input type="submit" value="Submit">
</form>
<span id="status" />
<img id="uploadedImage" />
</body>
</html>
I am getting an error that the req.files is undefined.
What could be wrong? The file upload is also not working.
As noted in the docs, req.files, along with req.body are provided by the bodyParser middleware. You can add the middleware like this:
app.use(express.bodyParser());
// or, as `req.files` is only provided by the multipart middleware, you could
// add just that if you're not concerned with parsing non-multipart uploads,
// like:
app.use(express.multipart());