I'm using ionic with angular.js for the front-end. I also setup a separate folder for my server side component. This is my index.js file...
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
As you can see it is a simple Hellow World example on my localhost.
I am going to use ngrok to make my server file public. My question is, after I do that, how can I call the index.js server file from ionic?
Do I call it from my angular module? If so, how can I do that? Can someone tell me what code is needed to add in ionic so I can connect to the server file? I am trying to use node js as my backend but having difficulty.
ngrok will allow you to access your localserver from outside your network.
Here is a basic example of how you call your server. Depends where you need to call it but this is how I do it using ngResource
angular.module('starter.services', ['ngResource'])
.factory('Session', function ($resource) {
return $resource('http://XXX.XXX.XXX.XXX:5000/sessions/:sessionId');
});
If you run your app from a browser with ionic server you can use http://localhost:5000.
If you use your phone and if it is on the same network than your server you can use your private IP, something like http://192.168.XXX.XXX
And if you want to try it from another network ngrok is a good choice.
Related
I have a React-Express app that pulls data from a MongoDB database on mLab.
On my server.js file, I have the api port set as such:
var port = process.env.PORT || 3001;
And it listens as such:
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
Currently, in my React app, one of the components makes an AJAX call to the database on mLab using the url of "http://localhost:3001/api/data", which works fine and pulls the data I requested.
However, when I deploy the app to Heroku, I'm not sure how to configure the server.js and the url in the React app, so the React app is able to pull the data from the database.
I've conferred with mLab, and there are no issues, and I've conferred with Heroku, and this is beyond the scope of their support.
UPDATE: Is it that the process.env.PORT variable needs to be set or redirected?
Any ideas what I need to do?
Thanks!
If your express app is serving both your bundled react app and your api, you need to make sure that express knows that the /api endpoint needs to be NOT served to the react app.
Not sure what your server code looks like, but this has worked for me:
if (process.env.NODE_ENV === 'production') {
app.get(/^\/(?!api).*/, (req, res) => { // don't serve react app to api routes
res.sendFile(PATHTOREACTBUNDLE));
});
};
Basically, you want to tell express that, if in production mode (deploy on heroku), serve all endpoints, except the api endpoint (/^/(?!api) to your react bundle.
So here is my issue in a pickle: btw I had some trouble finding out how to do this through google and I did try using StackOverflow but couldn't find the exact answer
So I have a ReactJS website where I use
yarn start
to run and it launches on localhost:3000
I want it to launch on localhost:3000 while an express server also launches on that server, aka start the react server up in express.js.
It seems like every tutorial I've found, most are outdated, and the remaining ones are guides to turn react into a static website and THEN use express. I would like to keep react on the server-side for advantage of react-router
Edit1: So basically when I have an expressjs server
THE DATABASE DETAILS HAVE BEEN REMOVED, THAT LINE ISNT AN ERROR
const express = require('express'); var app = express();
var mysql = require('mysql'); var connection =
mysql.createConnection({ host :
database : 'main' });
connection.connect()
app.post('/users', function(req, res) { var user = req.body;
res.end('Success'); })
app.listen(3000, function(){ console.log('Express sever is listening
on port 3000') })
//connection.end()
I also start the create-react-app server with yarn start and it launches on localhost:3000 but this expressjs server overrides that.
So I want to connect the two to be able to send post requests
I just recently worked on a sample repo that implements this strategy. There are a few ways this can be done, but the simplest way to do this will be to start the express server as a second server that will run on a different port, ie. 3001. You can then use concurrently to launch both the react server (I am assuming webpack) and the express API server in a single command.
Here is a tutorial that shows how this can be set up. You should pay attention to the section in this tutorial about proxying requests from the client (browser) through the webpack server. There are some considerations to think about with regards to CORS configuration if you do not proxy requests through the webpack server.
Here is my proof of concept repo where I implemented just what you are looking for: react client, and express server. It can be run via concurrently or with docker (compose).
You can change the port on which express is listening:
var server = app.listen(3001, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
Change 3001 to any valid port number
I have created a angularjs application without nodejs usage. I am using "chrome-add server extension" to run the app locally and using Bluemix cloud to deploy the files and run the app. I have created a java service in Bluemix and http.get to get the service to my front end. But I am facing an issue with CORS in the front end sometime. So I took a suggestion to create a nodejs file to get the service and integrate to angular controller instead of http get method.
My issue is that I don't want to create a server configuration in nodejs, just get the service in nodejs (app.get) and pass to angularjs controllers. The app is already invoked by the Chrome extension port.
The code i have written in nodejs server file is,
var express = require('express');
var app = express();
var express = require('express');
var app = express();
app.get('http://myblumemix-service.mybluemix.net/getDetails', function(req, res){
//code to bind the response to angular controller
//alert("");
//console.log("got already running port successfully");
});
app.listen("http://127.0.0.1:8887/");
But i am not able to get the response successfully to angular controller.
My question is, could we use nodejs without creating web server and only to pass the rest response to angular modules. As i am new to node and angular, is there any example to do this?
You cannot do your CORS handler URL that way. You will need to have a local path which proxies to the mybluemix URL, using something like https://github.com/request/request.
Example:
var request = require('request');
app.get('/getDetails', function(req, res){
request.get('http://myblumemix-service.mybluemix.net/getDetails').pipe(res);
});
Then the Angular code needs to use /getDetails URL instead of the full mybluemix one.
I have a Node/Angular app I'm trying to deploy. It uses two node servers: One to essentially serve the app; another to get data from an API, when a specific port is requested by the app, and store that data locally.
I've got it working perfectly on my own local machine. However, when I deploy to production environments -- either Heroku or AWS Elastic Beanstalk -- I find that the second script either won't run or won't start properly. The end result is, it doesn't get the data I need.
Here are the two scripts; they're both set to run in package.json under "start": "node main.js & node node-server.js"
main.js (again, this one seems to be serving the app just fine):
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/app'));
app.listen(process.env.PORT || 3000);
node-server.js (the one that doesn't seem to work; no data is gathered or populated in the app):
var http = require('http');
var port2 = 1234
var fs = require('fs');
//We need a function which handles requests and send response
function handleRequest(req, res) {
request.get({
url: 'http://sample-url.json',
qs: {
url: 'http://sampletool/pb/newsletter/?content=true'
}
}, function (err, result) {
res.end(result.body);
fs.writeFile('app/data.json', result.body, function (err) {
if (err) return console.log(err);
console.log('API data > data.json');
});
});
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(port2, function () {
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://0.0.0.0:%d", port2);
});
Then, the main Angular app calls this port (http://0.0.0.0:1234) when the page is loaded, to request new data.
Elastic Beanstalk is using nginx, something I'm not super familiar with and that I don't have running on my local.
Is there something big I'm missing in configuring multiple node.js servers to be running on different ports in a production environment? Thanks in advance for any help.
For security reasons, cloud service providers typically allow the usage of only one port (which is dynamically and randomly assigned to the PORT environment variable) for an application to use from a node server. Read this section from Heroku documentation to understand more about this.
This is why the main app (main.js) that uses process.env.PORT is working and the other app (node-server.js) that uses hard-coded 1234 is not.
This question has some pointers about the feasibility of multiple ports on Heroku (though, there is no good news there, I am afraid).
As how to go about fixing this, one thing that could be tried is to split this into two separate apps that are deployed separately with separate package.json etc.
I'm currently developing an Apache Cordova app with Ionic Framework that should communicate through a WebSocket and I use the Socket.Io library for it. Now when I run it on my desktop browser everything works fine but when I build for Android and test it on my Smartphone it doesn't work.
My Server looks like this:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8200, '192.168.0.127', function() {
console.log('Server listening...');
});
io.listen(server);
io.on('connection', function(socket) {
socket.emit('init', data);
});
And since Ionic is friends with AngularJS my Client Controller looks like this:
.controller('AppCtrl', function($rootScope, $scope, ServerUrl) {
var socket = io.connect(ServerUrl.serverUrl()); // ServerUrl: 'http://192.168.0.127:8200'
socket.on('init', function(data) {
// something
});
I included the Socket.IO Client script in my index.html head like this:
<script src="lib/socket.io/socket.io.min.js"></script>
When I remote debug the app it throws this repeatedly with different t parameters:
Failed to load resource: net::ERR_ADDRESS_UNREACHABLE http://192.168.0.127:8200/socket.io/?EIO=3&transport=polling&t=1431079993172-0
I've thoroughly searched every related question on here but they didn't solve my problem. I really need this thing to work and would appreciate any help.
Thanks in advance.
It was an IP address issue. 192.168.0.127 was the WiFi IP of my desktop but somehow everytime I connected my smartphone to my desktop to deploy the app a LAN network was build and the WiFi Adapter was disconnected so 192.168.0.127:8200 was out of reach. Deactivated the LAN network in Windows Control Panel and everything works fine.