I'm working on rendering the basic starting 'Hello, world' view of my Nodejs project based on the MVC model in this tutorial.
However, I couldn't believe after I wrote down bunches of js scripts, I tested with running the server script with node server.js, I kept getting this error as in the screenshot below:
I thought there was definitely something wrong with my Nodejs package Hapi with the incompatible version, but its version is even updated than the version used in the tutorial.
I checked the code line by line with the one given in the phase of the tutorial, but couldn't find anything wrong. So it should be something wrong in the server code. So what really goes wrong here? See the notes in the server.js code below:
'use strict';
//create all related dependencies
const Hapi = require('hapi');
const Hoek = require('hoek');
const Settings = require('./settings');
//instantiate server object with connection port of Settings
const server = new Hapi.Server();
server.connection({port: Settings.port});
//create a testing route and initiate the HTTP call
server.route(
{
method: 'GET',
path: '/',
handler: (request, reply) => {
reply('Hello, this is the Nodejs project for Dota2Insight');
}
}
);
server.start((err) => {
Hoek.assert(!err, err);
console.log(`Server running at: ${server.info.uri}`);
});
I'm very inexperienced with Nodejs.
Related
I have been working on a NodeJS express app that uses EJS and node-fetch to fetch my Api from my vps server, but it won't get fetched, every page of the app will load but the page that uses the Api where I am fetching the Api won't work, I have been trying to solve this issue for almost a week now but cannot get anywhere
My App.js
const express = require('express');
//node fetch used here is a fork of the original and i have tried both original and this
//both have the same result
const fetch = require('#formio/node-fetch-http-proxy');
const port = 3000;
...
...
... <- some code here
...
...
app.get('/', (req, res) => {
res.render('index');
});
app.get('/xyz',(req,res) => {
var url = 'http://XX.XX.XX.XX:8080/api';
try {
fetch(url, {
method: 'GET',
headers: {
'api-key': process.env.API_KEY,
'Content-Type': 'application/json'
}
}).then((resp) => {
return resp.json();
}).then((data) => {
...
... <- some code here
...
res.render('xyz',{categories: categories , ...});
}).catch((err) => {
console.log(err);
});
}
catch(err) {
console.log(err);
}
});
...
... <- some code here
...
Error I am getting :-
With both Axios and node-fetch I have been getting a common error of
connect ECONNREFUSED XX.XX.XX.XX:8080
Some of the things that I have tried :-
I have switched from Axios to node fetch thought maybe that had to do something with it, I have hosted a new node app on vps that when requested will show a msg in console that a request was made and pass the Json by locally fetching it, when I made a request from postman it worked the console logged 'Request was made' but when I tried it on the cPanel hosted app it did not show anything, I have also tried making my Api a https response but that did not work ether.
Note :-
The app is working fine when i host it in local pc, when i host the node app in cPanel it won't work.
Solution Found :-
because I am new to web developing and never used cPanel before, I had to allow my backend vps server Ip after contacting my web server provider he allowed the Ip and now it's working like a charm
So I have a node js code that updates and modifies a file content but I would like the data being inserted to come from a JavaScript code. How do I connect the two? Basically how do I have a function in node js that can be called from JavaScript?
Considering there's not much information to go off in the question, I am going to make a the assumption that you're trying to pass information from JS in a web browser to a node application.
The easiest and best documented way to do this would be to set up a simple web server using a package like expressJS and send data as a POST request using the fetch command in the browser.
Install express on the node application using the getting started guide
Write a http path where you can process the data
Start the node app
Make a call to the path we just created
Example backend code:
const express = require('express')
var bodyParser = require('body-parser')
const app = express()
const port = 3000
app.use(bodyParser);
app.post('/mypath', (req, res) => {
const myInputData = req.body.data;
//Do whatever you want with the data
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Example front-end code:
var data = new FormData();
data.append('data', YOUR_DATA_VAR_HERE)
var options = {
method: 'POST',
body: data
}
fetch('http://localhost:3000/mypath',options)
.then(function(response){ console.log("Data was sent successfully") })
.catch(function(error) { console.log("There was an error sending data") })
Hi guys i am new in nodejs when i am trying to run my node js file then Am getting an error like coneection closed due to error Error: Unsupported protocol "undefined" don't know where i am wrong please fix my error
https://ibb.co/31J6xWS
index.js
const http = require("http");
const fs = require("fs");
var requests = require("requests");
const homeFile = fs.readFile("home.html", "utf-8",(err)=>{
console.log("Sucessfully");
});
const server = http.createServer((req, res) => {
if (req.url == "/") {
requests(
"{API}",
)
.on("data", (chunk) =>{
console.log(chunk);
})
.on("end", (err) => {
if (err)
return console.log("coneection closed due to error",err);
console.log("end");
});
}
})
server.listen(8000,"127.0.0.1")
You have made a mistake in your pasting API key. Check your API key it will not be like URL.
http:// is missing at the beginning.
Add http:// in the start of your API key.
Are u trying to use a template literal on line 13... the "{API}" section. If so it should ${API} with backticks. And you need to import it from the file you have it in. Beginner to Node.js as well, and I have used something similar to this. Hope it helps. Have u seen https://www.npmjs.com/package/request? Might help you.
a better and easier way to build a server is by using Express.js library you can download it with the following command:
npm i express
more information: https://www.npmjs.com/package/express
after that you can build a server very easily with the following code :
// npm install express
const express = require('express');
const app = express();
app.get('/', (req, res)=> {
res.send('Hello World');
})
app.listen(3000,()=>{
console.log("starting...");
});
the following code is create a server listening on localhost port 3000 and print a message hello world
I was also facing the same problem. Here is the solution. Replace {API} with your API key.
requests("replace this with your API url and API key")
I have front-end folder files with react components and front-end css libraries.
In different folder, I have back-end files with server.js routing with mysql connection.
When I enter inputs on the screen, the inputs are not saved to mysql database.
Questions:
In what file, do I connect my front-end with back-end?
What statement should I use to connect my front-end with back-end?
To start Front-end, I used: npm start and To start Back-end, I used: nodemon server.js.
Question: When I connect front-end and back-end, what file should I open so that the front-end talks with the back-end -> both are starting?
Question 1 answer
You can do this a number of ways. I've done this with Serverjs and react in the
following manner.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 80085;
const app = express();
const token = 'impossiblylongimportanttokenhere';
let nextId = 7;
You'll need to import CORS, a Parser, Express for routing purposes.
Assuming you'll have a login you'll want a authenticator function. Please note this is just for development.
function authenticator(req, res, next) {
const { authorization } = req.headers;
if (authorization === token) {
next();
} else {
res.status(403).json({ error: 'User must be logged in to do that.' });
}
}
You'll probably want to replace that with something more secure once you're don with development.
with app as our router express has several CORS methods to get us started likepostget
Here's an example of one if we had an array called friends and if we wanted to find that friend by ID.
app.get('/api/friends/:id', authenticator, (req, res) => {
const friend = friends.find(f => f.id == req.params.id);
if (friend) {
res.status(200).json(friend);
} else {
res.status(404).send({ msg: 'Friend not found' });
}
});
The best part is that express has a method called listen that will start as soon as we hit NPM RUN on a cli that's parked in the same file location as server.js. Make sure to specify a port that your system isn't already using
app.listen(port, () => {
console.log(`server listening on port ${port}`);
});
Question 2
In order to get connect to Server.js on our side you'll want use axios to make a GET/POST etc. call to whatever route you've made in your server.js above in the example it would be
.post('/api/friends', this.state.addFriend)
The biggest thing is you'll want multiple terminals running in order to have both the backend and the front end running at the same time. Start with backend first.
After thorough researching, I decided to use Bluemix for classifying and recognizing images.
I'm have a starter question on how to begin programming using node.js runtime.
I tried to follow this tutorial. However, that is just snippets of code. How do you run them and see it working in the Bluemix environment?
My progress:
-I started the node.js starter application in Bluemix.
-I added the following code and the app.js looks like this:
/*eslint-env node*/
//--------------------------------------------------------------------------
// node.js starter application for Bluemix
//--------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
var watson = require('watson-developer-cloud');
var fs = require('fs');
/*var visual_recognition = watson.visual_recognition({
username: '<username>',
password: '<password>',
version: 'v2-beta',
version_date: '2015-12-02'
});*/
var visualRecognition = watson.visual_recognition({
version: 'v3',
api_key: process.env.API_KEY || 'my api key',
version_date: '2015-05-19'
});
var params = {
images_file: fs.createReadStream('./resources/car.png')
};
visualRecognition.classify(params, function(err, res) {
if (err)
console.log(err);
else
console.log(JSON.stringify(res, null, 2));
});
I'm trying to run the code in the Bluemix environment (live edit mode) and not locally. When I hit run the code, the deployment stops and I can't even locate what line of code is making this happen. When I visit the webpage I get the following error:
404 Not Found: Requested route ('myvisualapp.mybluemix.net') does not exist.
I don't understand what's wrong and how to debug the code.
Author level: beginner
You need to 'route' (or at least intercept) the client requests in express. Right now, the request do not have a handler. Use app.get() call for that purpose
Your watson service calls are unbounded to a user request right now. You need to funnel it through a user request.
For example:
app.get('/', function(req, res) {
// invoke watson services
// get the result.
// write back the result through the response object, res
}
You can look at the demo code at https://github.com/watson-developer-cloud/visual-recognition-nodejs and get a good place to start.
Also, from the command line you can see the logs of your application deployed into bluemix using
$ cf logs YOURAPPNAME --recent
where YOURAPPNAME is the name of the application you pushed to bluemix. You can get the name using
$ cf apps
if you forget the name you used (which happens to me all the time).