i have to design a simple webpage. that was click the Button then the command prompt will be open.
this is my aim
Below i have to mention the html code and node js code.
test.html
<html>
<head>
</head>
<body>
<p>guru</p>
<form action="/" method="post">
<input type="submit" value="Run"/>
</form>
</body></html>
the below code was node js sample.js
const express=require("express");
const bodyParser =require("body-parser");
const app=express();
const child_process=require('child_process');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine','ejs')
app.get('/',function(req,res){
res.render('test');
});
app.post('/',function(req,res){
res.render(
child_process.exec("cmd.exe" ,(err,stdout,stderr)=>{
process.stdout.write(stdout)
})
);
});
app.listen(8080);
console.log('listen');
after running the script i have faced the error:)
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object
give the suggestion
You have to pass a string to render.
Maybe you have to reverse the callback order to:
app.post('/',function(req,res){
child_process.exec("cmd.exe" ,(err,stdout,stderr)=> {
res.render(stdout)
})
});
Related
I'm frustrated because I can't send from HTML or receive from Node.js JSON data. I think that I'm near to resolve, but I'm tired trying for hours. Anybody helps me?
As the code below, the responde is null (req.body = null?) in my VSCODE.
When I try from Insomnia, that's ok. When I try from HTML Form, fails. *
I could to use BodyParser, but why to send from Insomnia works and from HTML Form doesn't?
//routes.js
routes.post('/go', (req, res) => {
console.log(req.body)
return res.json({ "Response": req.body })
})
<!DOCTYPE html>
<html>
<head>
<title>API Correios</title>
</head>
<body>
<form id="FrmQuery" action="http://localhost:3333/go" method="POST" enctype="application/json">
<label for="sCepOrigem">Cep Origem</label><br>
<input type="text" name="sCepOrigem" id="sCepOrigem"><br><br><br>
<input type="text" id="jsonData"><br><br>
<button id="send" type="button">Enviar</button>
</form>
<script>
document.querySelector('#send').addEventListener('click', (event) => {
let sCepOrigem = document.querySelector('#sCepOrigem')
var obj = {
"sCepOrigem": sCepOrigem.value,
};
var myJSON = JSON.stringify(obj);
document.querySelector('#jsonData').value = myJSON
document.querySelector('#FrmQuery').submit()
})
</script>
</body>
</html>
In Javascript from web browser you need to send it as raw XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Other possibilities would be jQuery's $.ajax or maybe the new fetch API.
Based on my experience with node js, I believe you have to simply res.send and cut out the return statement.
Hope this helps.
I want to use form input from HTML to JS. For that i am using following snippet but getting "SyntaxError: Unexpected token if" can anyone help in modifying it.
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile(html_form_path, function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
var q = url.parse(req.url, true);
var qdata = q.query;
res.write(qdata.Input());
}).listen(8080);
HTML FORM:
<html>
<body>
<form type='get'>
<input type="text" name='Input'>
<input type='submit'>
</form>
</body>
</html>
You should send data from html to server, you will need bodyparser and it is easiest to do if you also have express on server then you make submit button and i form tag add action and method atributes and on server you expect
app.post("/action",function(req,res){
req.body.input
})
html:
<form action='/action' method='POST' >
<input name=input''>
<input type='submit'>
</form>
also this will reload your page, if you want not to reload you need use ajax to send data you can use axios in javascript.
see express docs on how to set it up and you need see bodyparser docs and then use this code
Working on frontend and backend using NodeJs for server side and ejs template for frontend. Came across a feature while using ejs scriplets to display data send from server while loading page.
Used <%console.log()%> over ejs, thought this log will be seen on inspect element logs, however got message over server terminal. How did this information is send over to server without any form submit or API call?
Server app.js:
/*jshint multistr: true, node: true, esversion: 6, undef: true, unused: true, varstmt: true*/
"use strict";
// NPM Modules
const express = require('express'),
path = require('path');
const app = express();
// Setup views directory, file type and public filder.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.render('index', {message:'Welcome'});
});
const port = process.env.PORT || 3000;
console.log('server listening at http://127.0.0.1 over port: ', port);
app.listen(port);
EJS template index.ejs:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<!-- All these CSS files are in plublic directory, as we had made all the content of public directory available for anyone from app.js -->
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/app.css" />
<link rel="shortcut icon" href="logo.jpg" />
<title>Sign-Up/Login Form</title>
</head>
<body>
<%console.log(message)%>
<%=message%>
<%console.log("anything")%>
</body>
</html>
How can all the <%console.log()%> are send over server terminal and <%=message%> is displayed over browser. Even <%console.log("anything")%> is displayed over server terminal even though this has nothing to do with server. How ejs scriplets communicate with server and not browser?
Had anyone else tried this before or observed it.
Your question is about how ejs templates work. This is an answer for that question. I think you might also have something wonky going on with your express setup causing you problems.
EJS is a server-side rendering system. It's job is done before the html is sent to the client, so it has nothing to do with the browser.
The scriptlets inside <% %> run on the server to insert content into the template before sending to the client.
If you want to print something out on the browser console, don't put it in a scriptlet, just put it into a <script> tag, like this:
<script>
console.log("foo");
</script>
If you want the browser console to print something generated by the server, you could use ejs to put the value of message into what it generates:
<script>
console.log("<%=message%>");
</script>
The server will put the value of message into a console.log() statement that gets delivered to the browser.
This example prints "Wellcomes" to the browser console:
server:
const bodyParser = require('body-parser'),
express = require('express'),
path = require('path');
const app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.render('index', { message: 'Wellcomes' });
});
const port = process.env.PORT || 3000;
const listener = app.listen(port, function() {
console.log('platform listening on', listener.address().port);
});
index.ejs:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
</head>
<body>
<script>
console.log("<%=message %>");
</script>
</body>
</html>
If you show page source in your browser, you should see:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
</head>
<body>
<script>
console.log("Wellcomes");
</script>
</body>
</html>
I'm trying to learn express. I'm using FS to load my HTML Page. The only thing I could find on this with a google search was using ASP.NET instead of Express.
Server.js:
var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname+'/')))
app.get('/', function(a,b,c){
fs.readFileSync('index.html');
});
app.post('/testaction', function(a,b){
console.log(a.body.log);
fs.readFileSync('Logged.html');
});
app.listen(3000);
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<form method="post" action="http://localhost:3000/testaction">
<h1>Log This:</h1>
<input type="text" name="log"/>
<input type="submit", value="Press Me!"/>
</form>
</body>
</html>
In order to serve files you don't have to use fs. Example:
app.get('/', function(req, res, next) {
res.render('index');
});
If you need to redirect, you can use:
res.redirect('/staticFile.html');
Remove these lines:
app.get('/', function(a,b,c){
fs.readFileSync('index.html');
});
This line is middleware and it applies to all routes on every request:
app.use(express.static(path.join(__dirname+'/')))
It's purpose is to serve static files from whatever path you provide. In this case you're serving from the root directory so you can navigate to all your code files like http://localhost:3000/package.json for example.
It applies to all HTTP methods, get post put etc...
When you write app.get('/' you override that middleware with a new route and try serving only one file. Just drop that code and you'll server everything statically from the directory you specified above.
If you don't want to serve your code files, put your static files in a different folder such as "site" and set your static path to that folder, for example:
app.use('/', express.static(__dirname + '/site'));
this is form example in html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="/myaction" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
and this is node.js function that run on the server:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
switch (req.url)
case '/myaction':
res.end(?????);
break;
}
}).listen(8080);
sys.puts('Server running at http://127.0.0.1:8080/');
I have 2 questions:
How can I call myaction function in the node.js from the html page? Because the html file runs on port 80 and node.js on 8080 (when I try to move the node.js to port 80 it writes "// Unhandled 'error' event")
In the node.js function where I put "?????" how can I get data from the html form.
When I type req.html.body.name I don't get the data...
Using http.createServer is very low-level and really not useful for creating web applications as-is.
A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.
When you have, you can create a basic application to handle your form:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
You can make your form point to it using:
<form action="http://127.0.0.1:8080/myaction" method="post">
The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.
It might help to look at this answer, which is very similar to your quest.