Enoch Barcenas

Enoch Barcenas

1573094325

Handle CORS issue in Angular 8 and Node/Express Applications

In this tutorial, we will learn to handle CORS (Cross-Origin Resource Sharing) issue in Angular 8/9 and Node/Express Applications. To solve CROS related issues in Angular, we will manage proxy configuration settings.

To sort out CORS related problems in Node/Express Applications, we will be using a third-party plugin called cors and some backend settings.

Table of Contents

  1. Introduction to CORS
  2. Fixing CORS Issue in Angular 8/9
  3. Enable CORS in Node/Express Server
  4. Conclusion

Introduction to CORS

Cross-origin resource sharing (CORS) is a standard that manages communication between 2 or multiple domains.

CORS is a mechanism for accessing data on various domains, that data type could be images, stylesheets, js scripts, iframes, and videos. This mechanism is used for sharing restricted resources on a web page asked from a different domain.

Fixing CORS Issue in Angular 8/9

Angular server by default serves on localhost:4200 (PORT 4200) and suppose if your backend server is working on different port or domain, then the CORS issue will inevitably occur.

Enable CORS with Proxy Configuration Settings in Angular.

Now, we are setting proxy in backend. Let’s say we have a backend server working on http://localhost:3000/api and we want to pass all the API calls to http://localhost:4200/api backend server.

To enable CORS via proxy configuration, we need to generate a src/proxy.conf.json file inside the Angular root folder and also place the following code inside of it.

We used the secure property to enable the deliberate use of SSL.

We defined logLevel property, to verify whether or not our proxy is running correctly.

In order to explore more about proxy configuration please refer to proxy to backend article.

{
    "/api/*": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug"
    }
}

Define Proxy Configuration values in angular.json

To register a proxy configuration, we need to go to the angular.json file and place the following code inside the serve/options. It will set the src/proxy.conf.json file in our Angular app.

"architect": {
    "serve": {
            "builder": "@angular-devkit/build-angular:dev-server",
            "options": {
                "browserTarget": "project-name:build",
                "proxyConfig": "src/proxy.conf.json"
            },
          }
}

Now, you are all set to start dev server with current proxy configuration, run the given below command. Please restart the server if you make any update in your proxy conf file.

ng serve --open

Enable CORS in Node/Express Server

Now, we will learn how to enable CORS in the Express and Node js app. We will look at one of the most straightforward methods to configure CORS in the express by using a third-party package.

You can run the following command to add the cors package in node/express backend.

npm install cors --save

Next, you can add the below code to enable cors in Express server.

// server.js

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

/* server configuration here */

Finally, CORS is enabled in the node server.

The Access-Control-Allow-Origin: * header will be rendered when any request is made to your application. This header chooses which origin are authorized to access the server resources with CORS.

Here * wildcard allots access from any source.

Conclusion

Finally, we have completed how to solve the CORS issue in Angular 8/9 and Express/Node server. To enable CORS in Angular, we learned how to configure Proxy Configuration. Other than that, we also learned how to install and configure CORS configuration in the Node server using a third-party plugin.

#angular #node #express

What is GEEK

Buddha Community

Handle CORS issue in Angular 8 and Node/Express Applications

Chanthol Khom

1595660769

Hello,

I have this issue and tried to enable core on angular using proxy but still not work.

Enoch Barcenas

Enoch Barcenas

1573094325

Handle CORS issue in Angular 8 and Node/Express Applications

In this tutorial, we will learn to handle CORS (Cross-Origin Resource Sharing) issue in Angular 8/9 and Node/Express Applications. To solve CROS related issues in Angular, we will manage proxy configuration settings.

To sort out CORS related problems in Node/Express Applications, we will be using a third-party plugin called cors and some backend settings.

Table of Contents

  1. Introduction to CORS
  2. Fixing CORS Issue in Angular 8/9
  3. Enable CORS in Node/Express Server
  4. Conclusion

Introduction to CORS

Cross-origin resource sharing (CORS) is a standard that manages communication between 2 or multiple domains.

CORS is a mechanism for accessing data on various domains, that data type could be images, stylesheets, js scripts, iframes, and videos. This mechanism is used for sharing restricted resources on a web page asked from a different domain.

Fixing CORS Issue in Angular 8/9

Angular server by default serves on localhost:4200 (PORT 4200) and suppose if your backend server is working on different port or domain, then the CORS issue will inevitably occur.

Enable CORS with Proxy Configuration Settings in Angular.

Now, we are setting proxy in backend. Let’s say we have a backend server working on http://localhost:3000/api and we want to pass all the API calls to http://localhost:4200/api backend server.

To enable CORS via proxy configuration, we need to generate a src/proxy.conf.json file inside the Angular root folder and also place the following code inside of it.

We used the secure property to enable the deliberate use of SSL.

We defined logLevel property, to verify whether or not our proxy is running correctly.

In order to explore more about proxy configuration please refer to proxy to backend article.

{
    "/api/*": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug"
    }
}

Define Proxy Configuration values in angular.json

To register a proxy configuration, we need to go to the angular.json file and place the following code inside the serve/options. It will set the src/proxy.conf.json file in our Angular app.

"architect": {
    "serve": {
            "builder": "@angular-devkit/build-angular:dev-server",
            "options": {
                "browserTarget": "project-name:build",
                "proxyConfig": "src/proxy.conf.json"
            },
          }
}

Now, you are all set to start dev server with current proxy configuration, run the given below command. Please restart the server if you make any update in your proxy conf file.

ng serve --open

Enable CORS in Node/Express Server

Now, we will learn how to enable CORS in the Express and Node js app. We will look at one of the most straightforward methods to configure CORS in the express by using a third-party package.

You can run the following command to add the cors package in node/express backend.

npm install cors --save

Next, you can add the below code to enable cors in Express server.

// server.js

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

/* server configuration here */

Finally, CORS is enabled in the node server.

The Access-Control-Allow-Origin: * header will be rendered when any request is made to your application. This header chooses which origin are authorized to access the server resources with CORS.

Here * wildcard allots access from any source.

Conclusion

Finally, we have completed how to solve the CORS issue in Angular 8/9 and Express/Node server. To enable CORS in Angular, we learned how to configure Proxy Configuration. Other than that, we also learned how to install and configure CORS configuration in the Node server using a third-party plugin.

#angular #node #express

Kyle  M. Farish

Kyle M. Farish

1567736377

Angular 8 Node & Express JS File Upload

In this Angular 8 and Node.js tutorial, we are going to look at how to upload files on the Node server. To create Angular image upload component, we will be using Angular 8 front-end framework along with ng2-file-upload NPM package; It’s an easy to use Angular directives for uploading the files.

We are also going to take the help of Node.js to create the backend server for Image or File uploading demo. Initially, we’ll set up an Angular 8 web app from scratch using Angular CLI. You must have Node.js and Angular CLI installed in your system.

We’ll create the local server using Node.js and multer middleware. Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. Once we are done setting up front-end and backend for our File uploading demo then, we’ll understand step by step how to configure file uploading in Angular 8 app using Node server.

Prerequisite

In order to show you Angular 8 File upload demo, you must have Node.js and Angular CLI installed in your system. If not then check out this tutorial: Set up Node JS

Run following command to install Angular CLI:

npm install @angular/cli -g

Install Angular 8 App

Run command to install Angular 8 project:

ng new angular-node-file-upload

# ? Would you like to add Angular routing? No
# ? Which stylesheet format would you like to use? CSS
cd angular-node-file-upload

Show Alert Messages When File Uploaded

We are going to install and configure ngx-toastr an NPM package which helps in showing the alert message when the file is uploaded on the node server.

npm install ngx-toastr --save

The ngx-toastr NPM module requires @angular/animations dependency:

npm install @angular/animations --save

Then, add the ngx-toastr CSS in angular.json file:

"styles": [
    "src/styles.css",
    "node_modules/ngx-toastr/toastr.css"
]

Import BrowserAnimationsModule and ToastrModule in app.module.ts file:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
 
@NgModule({
  imports: [
    CommonModule,
    BrowserAnimationsModule, // required animations module
    ToastrModule.forRoot() // ToastrModule added
  ]
})

export class AppModule { }

Install & Configure ng-file-upload Directive

In this step, we’ll Install and configure ng-file-upload library in Angular 8 app. Run command to install ng-file-upload library.

npm install ng2-file-upload

Once the ng2-file-upload directive is installed, then import the FileSelectDirective and FormsModule in app.module.ts. We need FormsModule service so that we can create the file uploading component in Angular.

import { FileSelectDirective } from 'ng2-file-upload';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    FileSelectDirective
  ],
  imports: [
    FormsModule
  ]
})

export class AppModule { }

Setting Up Node Backend for File Upload Demo

To upload the file on the server, we need to set up a separate backend. In this tutorial, we will be using Node & Express js to create server locally along with multer, express js, body-parser, and dotenv libraries.

Run command to create backend folder in Angular app’s root directory:

mkdir backend && cd backend

In the next step, create a specific package.json file.

npm init

Run command to install required dependencies:

npm install express cors body-parser multer dotenv --save

In order to get rid from starting the server again and again, install nodemon NPM package. Use –-save-dev along with the npm command to register in the devDependencies array. It will make it available for development purpose only.

npm install nodemon --save-dev

Have a look at final pacakge.json file for file upload demo backend:

{
  "name": "angular-node-file-upload",
  "version": "1.0.0",
  "description": "Angualr 8 file upload demo app",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Digamber Rawat",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.17.1",
    "multer": "^1.4.1"
  },
  "devDependencies": {
    "nodemon": "^1.19.1"
  }
}

Create a file by the name of server.js inside backend folder:

Configure Server.js

To configure our backend we need to create a server.js file. In this file we’ll keep our backend server’s settings.

touch server.js

Now, paste the following code in backend > server.js file:

const express = require('express'),
  path = require('path'),
  cors = require('cors'),
  multer = require('multer'),
  bodyParser = require('body-parser');

// File upload settings  
const PATH = './uploads';

let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, PATH);
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

let upload = multer({
  storage: storage
});

// Express settings
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

app.get('/api', function (req, res) {
  res.end('File catcher');
});

// POST File
app.post('/api/upload', upload.single('image'), function (req, res) {
  if (!req.file) {
    console.log("No file is available!");
    return res.send({
      success: false
    });

  } else {
    console.log('File is available!');
    return res.send({
      success: true
    })
  }
});

// Create PORT
const PORT = process.env.PORT || 8080;
const server = app.listen(PORT, () => {
  console.log('Connected to port ' + PORT)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

Now, while staying in the backend folder run the below command to start the backend server:

nodemon server.js

If everything goes fine then you’ll get the following output:

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
Connected to port 8080

Create Angular 8 File Upload Component

In this last step, we are going to create a file upload component in Angular 8 app using Express js API.

Get into the app.component.ts file and include the following code:

import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
import { ToastrService } from 'ngx-toastr';

const URL = 'http://localhost:8080/api/upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  public uploader: FileUploader = new FileUploader({
    url: URL,
    itemAlias: 'image'
  });

  constructor(private toastr: ToastrService) { }

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };
    this.uploader.onCompleteItem = (item: any, status: any) => {
      console.log('Uploaded File Details:', item);
      this.toastr.success('File successfully uploaded!');
    };
  }

}

Go to app.component.html file and add the given below code:

<div class="wrapper">
  <h2>Angular Image Upload Demo</h2>

  <div class="file-upload">
    <input type="file" name="image" ng2FileSelect [uploader]="uploader" accept="image/x-png,image/gif,image/jpeg" />
    <button type="button" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
      Upload
    </button>
  </div>

</div>

Now, It’s time to start the Angular 8 app to check out the File upload demo in the browser. Run the following command:

ng serve --open

Make sure your NODE server must be running to manage the backend.

When you upload the image from front-end you’ll see your image files are saving inside the backend > uploads folder.

Conclusion

In this Angular 8 tutorial, we barely scratched the surface related to file uploading in a Node application. There are various other methods available on the internet through which you can achieve file uploading task quickly. However, this tutorial is suitable for beginners developers. I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

#angular #angular-js #node-js #express #web-development

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Clara  Gutmann

Clara Gutmann

1598716260

Angular 8 CRUD Example | Angular 8 Tutorial For Beginners

Angular 8 CRUD is a basic operation to learn Angular from scratch. We will learn how to build a small web application that inserts, read data, update and delete data from the database. You will learn how to create a MEAN Stack web application. In this Angular 8 Tutorial Example, you will learn a new framework by building a crud application.

New features of Angular 8

You check out the new features in brief on my  Angular 8 New Features post.

I have designed this Angular 8 CRUD Tutorial, especially for newcomers, and it will help you to up and running with the latest version of Angular, which is right now 8.

#angular #angular 8 #angular 8 crud

Roberta  Ward

Roberta Ward

1595344320

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill.

Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.

Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!

And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!

If you are still not aware of it, don’t worry as Georgia Byng has well said,

“No time is better than the present”

– Georgia Byng, a British children’s writer, illustrator, actress and film producer.

No matter if you are a developer (be it front-end or back-end) or a data scientisttester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.

From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.

How to upgrade your skills?

Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.

These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.

Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).

xlr8rs make your development real fast by just adding your core business logic to the template.

If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂

Confused with which technology to start with?

To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.

Since we believe:

“There’s always a scope of improvement“

If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.

#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade