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.
Related
The main goal is to return an HTTP status code different than 200, but only after the API call response, which will notify us if the page is found or not found.
From what I’ve read, there is no way to accomplish this except using an SSR, which acts as a server and can set a status code.
If there is another way to do this we can skip the SSR part.
I need help to integrate the SSR into the NOT fresh install Angular 8 Project.
I have compiled the SSR code and have also set the express server running.
The problems I have are the following:
The express server parses only the main request (the one from the browser URL bar) but the API calls made from Angular are not passing through the express server. I’m using the HttpClient wrapped in service for better usage.
Therefore I cannot check what status code the API call is returning and then set it as a page response. This affects the SEO of the website and all pages (found or not found) are marked with status 200.
The window object is missing when express js server is serving the content. This is expected but I need the window and document objects because we have some jQuery libraries running along with Angular.
The app stopped acting like an Angular app and per every link click the page gets reloaded
What is the correct way to set the express server to serve the content to the Apache server which is handling the domain. Proxy or maybe some other service?
You can try to use a simple express server without the SSR.
Then just simply serve the compiled application through the express server and make the initial call to the API through the express server.
After that you can set the status code before the Angular is loaded
"use strict";
const express = require("express");
const compression = require("compression");
const nodeFetch = require("node-fetch");
const _port = 4100;
const _app_folder = 'dist/browser';
const app = express();
app.use(compression());
// ---- SERVE STATIC FILES ---- //
app.get('*.*', express.static(_app_folder, {maxAge: '1y'}));
// ---- SERVE APLICATION PATHS ---- //
app.all('*', function (req, res) {
let url = 'http://example.com' + req.url;
nodeFetch(url).then(apiRes => {
if(apiRes.status == 404){
res.status(404).sendFile(`/`, {root: _app_folder});
} else {
res.status(200).sendFile(`/`, {root: _app_folder});
}
})
});
// ---- START UP THE NODE SERVER ----
app.listen(_port, function () {
console.log("Node Express server for " + app.name + " listening on
http://localhost:" + _port);
});
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.
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.
I have a AngularJS application that I launch from a gulp command line
and run on port 3000.
In this app, as it's in a development state, I have some http requests like this one :
$http.get("http://localhost:8080/myapi/customers")
.then(function(response) {$scope.names = response.data.records;});
The gulp script minifies, uglifies and syncs changes with the browser.
The myapi is a NodeJS / Express simple app that runs with this command :
node myapi.js
What I want to achieve is giving the relative URL to the api instead of giving the full URL just like this :
$http.get("/myapi/customers")
.then(function(response) {$scope.names = response.data.records;});
How can I do that ? I could find resources about unifying APIs and AngularJS apps domains.
Regards
I'm using AngularJS and ExpressJS and having an issue with routing. I saw many other posts but none of those solutions seemed to work. Here is my routes in Express:
module.exports = function(app, auth) {
//Api routes
var mycontroller = require('../app/controllers/mycontroller');
app.get('/api/dostuff/:id', mycontroller.getBlockByHash);
//Home route
app.get("/", function(req, res) {
res.render('index');
});
};
When I go to my root /, everything works as expected. ExpressJS serves up my index and angular picks up the rest. When I click a link /blocks, it works as expected since AngularJS picks up the route. But when I refresh, I get a 404 not found error.
I tried app.get('*' instead, but that gives me a completely different error where nothing loads.
I'm using Jade to create the basic page structure with Express. My Express config is:
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
When using html5Mode the documentation says:
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
What it doesn't mention is:
You should exclude static assets like scripts/styles/images/fonts etc.
You should also exclude your Restful API.
Your case:
The error you got there is express serving html into script tags and the browser fails to parse them as a valid javascript.
Use express.static to serve static assets and then use app.get('*', for redirecting all other requests to your angular.js entry point (index.html).
express.js middleware order do counts!
express.static must be declared before app.router
Node.js / Express.js - How does app.router work?