I am working on a project. Where i need to call a web service which returns a SOAP message. Now the problem is that the webservice is hosted on an IntraNet and i can not access it. I have been provided with a txt file that contains a sample response of the web service.
I have to manipulate the reply in my code
Is there anyway I can call this txt file instead of the web service and get the response and manipulate it ?
You can do that using node and Express JS.
Install Node from www.nodejs.com
after installing and running node, go to your directory and install express :
npm install express
then create a file called app.js and run it with node : node app.js
app.js file:
var express = require('express')
, app = module.exports = express();
app.get('/', function(req, res){
res.send('<p>Static File Server for files</p>');
});
app.get('/txt/:file(*)', function(req, res, next){
var file = req.params.file
, path = __dirname + '/public/txt/' + file;
res.sendFile(path);
});
if (404 == err.status) {
res.statusCode = 404;
res.send('File Does Not Exist!');
} else {
next(err);
}
});
if (!module.parent) {
app.listen(8023);
console.log('Express started on port 8023');
}
put the folder that has your txt file in /public/txt/ so public and the app.js are in the same directory. you should run the app.js with node after this is done.
go to your web browser : navigate to localhost:8023/txt/yourfile.txt and if everything is working find you should be able to get the file.
Related
I have created a simple Express JS app. and it is working fine in localhost. when I visit localhost:8000 I see static files (index.html, style.css and frontend.js).
I have tried to deploy that app in a server using cPanel. and I have installed Node app and dependencies using package.json successfully. But when I visit the domain I just see a message (Node JS app is working, Node version is 10.24.1).
How to make my app to point and display the static folder (index.html) and run the app?
My app architecture:
server.js
package.json
public/index.html
public/style.css
public/frontend.js
And here is my server.js startup file:
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Dependencies */
const bodyParser = require('body-parser');
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('public'));
// Setup Server
const port = 8000;
const server = app.listen(port, function(){
console.log(`server running on localhost: ${port}`);
});
//POST Route to store data in the app endpoint, projectData object
app.post('/addData', addData);
function addData (req, res){
let data = req.body;
projectData = data;
console.log(projectData);
}
app.get('/getData', getData);
function getData(req, res) {
res.send(projectData);
}
The problem here is that you are not pointing a route to send the HTML file. Otherwise the client would have to point it to the correct path of the file, Like localhost:3000/index.html.
you need to send it from the server using app.get
app.get("/", (req, res) => {
res.sendFile(__dirname + "path to the file");
});
The problem was that I have created the app in a subfolder of my domain.
But when I have created subdomain and reinstalled the app inside it, the app is pointing to static folder successfully.
so, today when i'm going to save my javascript code, i've saved it with other extension, and the code is compiled successfully
//server.mp3
var express = require('express');
var app = express();
app.get("/", function (req, res) {
res.sendFile(__dirname + '/index.html')
})
app.listen(3000, function () {
console.log("Listening at 3000")
});
when i said :
node server.mp3
my server is running on port 3000...
how it is possible?
Node.js doesn't do different things depending on what type of file you open with it. It therefore doesn't try to determine what type of file you have given it based on the file extension. It just tries to execute it as JS.
I'm new on Nodejs.
I have to do a web app with node js, express, socket.io on an existing website.
I use JXcore on Parallels Plesk panel to execute node.
But when I run js file and I visit any page on the website it returns "Cannot GET ".
If I use express get() function:
var app = require('express')();
var http = require('http').Server(app);
var path = require('path');
app.get('/path/to/index.html', function(req, res){
res.sendfile( path.resolve(__dirname + '/index.html') );
});
http.listen(10500, function(){
console.log('listening on *:10500');
});
it works on /path/to/index.html but every other website page is blocked by the same error "Cannot GET ".
Is there a way to run node only on one page?
Thanks
What your code is doing is defining just one route /path/to/index.html and mapping that to your index.html file. If you want to serve files from a directory, static html/css/js/whatever files, you can use the static method express provides:
app.use("/", express.static(__dirname + '/myHtmlDirectory'));
Change the "myHtmlDirectory" to whatever directory you store your files in and make sure to change the includes to define express:
var express = require('express');
var app = express();
However, if you want all GET requests to point to one single file, index.html for example, you can use the following:
app.get('*', function (req, res) {
res.sendfile( path.resolve(__dirname + '/index.html') );
});
I use Windows 7. I installed nodes 0.10.12 and latest version of express and express-generator both globally. I
created a new express project named nodetest1 and installed all dependencies succesfully using npm install.
Going to http://localhost:3000/ renders Express Welcome to Express -so it works.
I try to use node and express as simple server now, just use some html files.
According to the book "Jump Start Node.js" by Don Nguyen Copyright © 2012 SitePoint Pty. Ltd. [pages 9-11] , I edited my
app.js file and added
var fs = require('fs');
and after
var routes = require('./routes/index');
var users = require('./routes/users');
I added
app.get('/form', function(req, res) {
fs.readFile('./form.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
});
Then I created a simple form.html file put it in the nodetest1 directory, restarted my server and in the command line I get
app.get('/form', function(req, res) {
TypeError : Cannot call method 'get' of undefined
npm ERR! weird error 8
npm ERR! not ok code 0
What am I doing wrong? I just want to use simple html, not Jade.
Also do I have to edit the app.js for every html file I add? And where will I add the new files, in what folder?
Thanks in advance
Did you create the express app?
var express = require('express');
var app = express();
Also, you can just use res.sendFile for this.
app.get('/form', function(req, res) {
return res.sendFile('form.html');
});
If you are serving up a lot of static files you may want to look into express.static middleware.
http://expressjs.com/4x/api.html#app.use
This will serve up all files you put in your public directory:
app.use(express.static(__dirname + '/public'));
Directory structure:
|-app.js
|-public
| |-index.html
| |-form.html
You're form.html will be served to localhost:3000/form.html
If you wan't to serve up html files without an extension you can use the solution found in this other answer to a different question by #robertklep.
Any way to serve static html files from express without the extension?
app.use(function(req, res, next) {
if (req.path.indexOf('.') === -1) {
var file = publicdir + req.path + '.html';
fs.exists(file, function(exists) {
if (exists)
req.url += '.html';
next();
});
} else {
next();
}
});
You'll want this to be before app.use(express.static(__dirname + 'public'));
Note: The book you mentioned was published Dec 2, 2012. Express 3 was released Oct 23, 2013 according to github. The current version is 4.8.5. You may want to use a more current reference.
I am new to Express and semi-new to nodejs and I am trying to run a simple app / webserver as a proof of concept. I have been stuck for hours because my server serves every file as index.html (with the content of index.html).
In my index.html I am making calls to JS files and CSS files and they are all coming back but with a 200 in the console but they are all coming back with index.html content instead of the actual content contained in them. I believe the problem is in my server.js file which is below:
// server.js
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
var path = require('path');
// configuration ===========================================
// config files
var db = require('../config/db');
var port = process.env.PORT || 9999; // set our port
//mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('../../app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:9999
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
// app/routes.js
module.exports = function(app) {
// server routes ===========================================================
// handle things like api calls
// authentication routes
// sample api route
app.get('/api/nerds', function(req, res) {
// use mongoose to get all nerds in the database
Nerd.find(function(err, nerds) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(nerds); // return all nerds in JSON format
});
});
// route to handle creating (app.post)
// route to handle delete (app.delete)
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('/Users/...../app/public/index.html'); // load our public/index.html file
//res.sendfile(path, {'root': '../'});
});
};
I have been following this tutorial verbatum: http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application but haven't had much success.
I cannot confirm without looking at your computer but I get the feeling the paths in your application are wrong.
The crucial parts in the express setup are:
app.use(express.static(__dirname + '/public'));
and
app.get('*', function(req, res) {
res.sendfile('/Users/...../app/public/index.html');
The first rule catches and returns any static file in __dirname + '/public'.
The second returns index.html for anything else.
The problem is that your server.js is not in the apps directory (I can see this since you use ../../app/routes.js to get to routes.js) this means __dirname + '/public' is not pointing to the public directory. Which is why your static files are being served by the global rule in routes.js.
In order to fix this change __dirname + '/public' to ../../app/public, or better yet place your server.js file where it should be and update your paths.
I can also see you are using an absolute full path to index.html in routes.js instead of a relative one so it seems as if your applications needs to tidied out.
The tutorial that you are following contains this route
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
which explicitly defines the behaviour you described.
In this tutorial it makes sense because it explains how to build a single page application. This type of the application typically returns the same content for all the request while the actual presentation work happens on the client by the client-side library (angular in this example).
So if you what to serve more pages with different content you need to add more routes for them, just like route for /api/nerds in the example.
Update:
After clarifying that the issue is incorrectly served CSS and JS files, the proposed solution is to check the location of the server.js - it should be in the folder together with the folder "public".