Cross domain issue for Express js and Angular Js - javascript

I have a node.js rest api built with Express framework version 4.11.1 and hosted in a server 'abc.com:5142'. Also have a front end website built with cg-angular which is hosted on the same domain but a different port 'abc.com:7070'.
When I access the front end causes a cross domain issue. I have tried almost all solutions including cors npm package. But it is not working.
Any help would be appreciated.
Thanks

Try this (keep the order):
var expr = require('express');
var app = expr.express();
var cors = require('cors');
app.use(cors());

Related

how to configure nodejs to accept all request from outside of localhost?

I developed an application with NextJs then built it. I run it on node server using
'npm run start' at Powershell. it works fine on localhost on port 80, but my server does not accept any request from outside neither by domain name or IP address. how should I configure application or nodejs to accept all request ?
OS is windows server 2019
You need to allow CORS
res.header('Access-Control-Allow-Origin', '*');
Try to this cors npm module - https://www.npmjs.com/package/cors
var cors = require('cors');
var app = express();
app.use(cors());
It provides many features to configure cors setting including domain whitelisting, enabling cors for specific apis and many more.

Can't get 'var express = require("express")' to work

I am new to js and I am trying to develop a simple node.js-mysql app. No matter what I do I can't get the standard
var express = require("express");
statement to work.
I have installed node.js and express correctly, express is in package.json. I have a local server running. But this simple line will not work.
On the node.js side at Windows command line I have no error but when I go to localhost:3000 on the browser, I get
'Uncaught Error: Module name "express" has not been loaded yet for
context: _. Use require([])' error at js console.
I tried changing it to
require(['express']`, function (express) {}
as suggested at node.js web site but then at the Windows command terminal I get a different error saying like
'expecting a string but received an array....'.
I have tried import instead of require and I have tried every suggestion that I could find on the Internet. I have been blowing my brains for weeks to get this to work with no success. I am so frustrated that I am seriously thinking about giving up all together. If someone can help I will be forever greatfull to him/her.
My main js code is as follows:
var port = 3000;
// Import or load node.js dependency modules.
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies.
app.listen(port, () => {
console.log(`server is running at http://127.0.0.1:8887`);
});
app.get('/', function(req, res){
res.sendFile("D:/Behran's files/Web projects/havuzlusite/index.html");
});
Require.JS is for loading AMD modules (and is, honestly, obsolete in today's JS landscape).
Node.js modules are either ECMAScript modules (which use import and export) or CommonJS modules (which use require and module.exports).
Even though both AMD and CommonJS modules use a function named require they are not compatible.
There are methods you can use to run ES modules and CommonJS modules in the browser however they can't replace APIs that are provided by runtimes.
Express.js needs to be able to listen for incoming HTTP requests. Browsers do not provide any mechanism to make that possible. Node.js does.
If you want to run Express.js you have to run it using Node.js and not a browser.
Express.js creates an HTTP server. A browser can make requests to it (e.g. if you type http://127.0.0.1:3000 into the address bar.
(Your code says server is running at http://127.0.0.1:8887 but the port constant is set to 3000).
All your Express.js code must run through Node.js.
You can't send a copy of that code to the browser and run it there too.

Node.js file to run a local server with access-control-allow-origin

I have an html file that has resources in it's directory
(example file tree)
index.html
imgs
>img1.jpg
>img2.jpg
>img3.jpg
js
>js1.js
>js2.js
How do I run a node.js server that will allow me to view the HTML file, as well as allow me to access certain websites with the access-control-allow-origin *
I am unfamiliar with node, so the simpler, the better!
Extra: does not necessarily have to be node, just a server that will allow access control
Since You're learning and starting from scratch so it's preferred to learn how it's done than installing supper-pupper swiss knife toolset that will hide the logic from You and make You boring lazy developer.
If You just want to achieve quick result and don't want to learn - You may use serve package that will do what You need.
But if You're learning nodejs from zero to hero so read my answer.
It's better to do simple things.
Let's go (:
Create some folder and inside of it do following commands in terminal (or cmd in windows os):
1) Init app:
npm init
2) Install express module:
npm i --save express
3) Install cors module/middleware:
npm i --save cors
4) Create public folder and put Your html files there
5) Create app.js file in sibling folder with public:
"use strict";
const
express = require('express'),
app = express(),
cors = require('cors');
app.use(cors()); // attach cors middleware (must be set before of most route handlers to populate appropriate headers to response context)
app.use('/', express.static('public'));
app.listen(8080, () => console.log('APP STARTED'));
6) Run it: node app.js
7) Open in browser: http://127.0.0.1:8080
for more stuff search in YouTube for nodejs express tutorials, nodejs mean stack tutorials and etc. (:
For a quick resolution it can also be checked, the Chrome Web server app, for creating local server allowing access to the local files over localhost server.
https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

Point domain to node express server on Azure

This must be an extremely common problem. I've seen various answers for this but none seem to work for me.
I have node installed on an apache server on Windows Azure. My app is built and ready to go (snippet below):
var express = require("express");
var app = express();
//example api call
app.get("/api/example", function(req, res){
//do some process
res.send(data);
});
app.listen(8080);
console.log("App listening on port 8080");
Now, when testing on my own computer, I could then go to localhost:8080, which works great. But now I've put it on the azure server I can't get an external domain to point to it properly. So for example, I have the domain:
framework.example.com
I've added this to my hosts file in Azure:
XXX.0.0.01 framework.example.com
Initially I tried also editing the http-vhosts.conf to point the domain to the correct directory. This worked for loading the frontend, but the app couldn't talk to the backend. API calls returned 400 not found errors.
I've also tried an Express vhost method but think I'm doing it wrong and don't fully understand it. What is the correct method?!
My app structure is like this:
- package.json
- server.js
- server
- files used by server.js
- public
- all frontend files
So to boot the server I run server.js which runs the code at the top. The server.js uses the below Express config to point to the public folder.
app.use(express.static(__dirname + "/public"));
Adding it to the hosts file in Azure won't help. You'll need to configure your domain's DNS to point to Azure. I'd recommend using the DNS Name of your Cloud Service instance. Your underlying VM IP address could change if you need to stop it for some reason, but your Cloud Service DNS name is configured to always route to your underlying VMs. That means you'll need to setup a CNAME with your DNS.
Read more about that here: Cloud Services Custom Domain Name
Next, you'll either need to host the node app on port 80, or put a proxy in front of it to handle that for you. Otherwise you'll be stuck typing framework.example.com:8080 which is not ideal. On linux, you'll likely need to be a privileged user to host on port 80, but you never want your node app to have root privileges. You can use authbind to work around this problem.
See an example of how to use it with node here: Using authbind with Node.js
All that being said, it seems like you're somewhat new with linux server management. If that's the case, I'd strongly recommend trying to use something like Azure Websites instead of a VM. You no longer have to manage the virtual machine OS. You simply tell it to host your application and it takes care of the rest. If you're using github, this is incredibly easy to test and iterate with. It does host on Windows under the hood, and that might problems for some applications, but I host all my node sites there (developed on Mac) without any issues.

How to configure expressjs/socketio webchat on ubuntu server

I wasn't sure if this is appropriate on the Ubuntu exchange or here but it is mostly code related i believe.
So I have created a neat working little web-chat application using socket.io which I've been developing on my Win10 pc using Git-bash and running it on my localhost with node.js and everything has been working just fine.
Thus I have come to a point where I would like to try out my app on my web-server.
Lets get more detailed what my Problems are:
I am unsure of how my server.js file should listen or open up the ports so to speak.
I have tried looking in the sockets.io chat example and tried their method yet the '../..' module leaves me confused.
Following the express.js site tutorial I actually get my server to respond listening on port 3000 yet my website returns the no socket.io/socket.io.js found.
this and this just lead to another localhost tutorial
In Short I have come to the point where when i do node server.js It seems to start listening here's the code to that part:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var port = process.env.PORT || 3000;
app.get ('/', function(req,res) {
res.sendFile(__dirname + '/index.html');
});
app.use("/static", express.static('./static/'));
server.listen(3000);
But now the problem is is that my html file cannot seem to find the socket.io/socket.io.js file, even though i have installed sockets.io, i consulted to this stack question which should fix it, but it didnt thus leads me to believe theres a thicker more server side issue?
Versions i am using:
express: **4.16.4**;
node : **10.15.0**;
npm : **6.4.1**;
socket : **2.2.0**;
EDIT: Added my html code snips
html
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="static/index.js"></script>

Categories

Resources