Cross-Origin Resource Sharing using Express.js and Angular2

Currently, I am attempting to download a PLY file from my Express.js server to my Angular/Ionic application which is currently hosted on Amazon AWS. Here is the Typescript code snippet from my Ionic app:

//this.currentPlyFile contains the entire URL
document.getElementById('entity').setAttribute("ply-model", "src: url(" + this.currentPlyFile + ".ply);");

Within my Express.js server, I have the following setup:

app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Credentials', true);
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET,POST');
        res.header('Access-Control-Allow-Headers', 'appid, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
        if ('OPTIONS' == req.method) {
            res.send(200);
        } else {
            next();
        }
    });

However, when trying to request the PLY file, I encounter the following error:

XMLHttpRequest cannot load "my url here" No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'my url here' is therefore not allowed access.

Despite using the CORS headers provided by Express.js documentation, I am still facing this frustrating issue.

Answer №1

In order to set up CORS, navigate to Preflight, then Options and refer to this link for more information: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS, followed by using next().

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'appid, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});

app.get('/', function (req, res) {
  res.send('OK');
});

Note: It is recommended to move the above code to the beginning of your configure function.


Alternatively, you can simplify the process by using express cors:

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

app.use(cors());

app.get('/', function (req, res) {
    res.send('OK');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Encountering file upload issues using express-fileUpload

I am encountering an issue when trying to upload a file to the server, any assistance would be appreciated Below is the command used to receive a file from the client and store it in the uploads folder exports.adminSendFile = (req, res) => { if (req.f ...

What are the reasons for my Node.js application's deployment process not finishing on Heroku?

I'm facing an issue while trying to deploy a nodejs app on heroku. The build process doesn't complete; it stops once the server starts running. I have attached some images of my application: Server Configuration const express = require(&ap ...

What are the steps for updating an NPM package that was installed from a Git repository?

I'm struggling to understand how to update a package that was installed from a git repository. Let's say I have a package located at git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b3bda094b3bda0b8b5b6fab1 ...

Having trouble with CSS compilation for new imported files (NPM Compile:SASS) - seeking assistance

As a complete beginner in SASS, I am just starting out. The package compile:sass is functioning perfectly, but the issue arises when I create a new scss file. I find myself having to restart my SASS compiler and live-server package each time in order for t ...

Chrome gets shut down by Browsersync

I currently have MAMP PRO 5.7 installed on my MacBook Pro (8GB RAM). The websites load at sitename.local.companyname.as on port 80 using WordPress, nginx, and MySQL. I'm also utilizing VSCode with composer, Gulp, and browsersync for development purpos ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

Locating the right selector for adding a div to its parent element in jQuery

I have come across an interesting HTML structure: <div class="dropdownedit"> <div class="dropbtn">textxyz</div> <div class="dropdown-content" style="display: none;"> <div href="#" class="ocond" id="text1">text1</div> &l ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...

What is the method for selecting an element using CSS code in Protractor?

Having trouble clicking on the element with CSS Selector: <button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view"> <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i> </button> This is what I've t ...

Guide to hosting an Angular 2 client app and Node server app simultaneously on one server

After creating an app in Angular 2 to retrieve data from a database and utilizing node/express to get data from the server and share it with the Angular client, both are currently operating on separate local hosts. How can I integrate them into one proje ...

Leverage jQuery to Retrieve Text and Modify

My Content Management System automatically generates a time stamp for when a page was last updated. However, the format it provides is not ideal for my needs. I would like the date to be displayed in the US Standard way - May 24, 2013, without including th ...

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

Node.js: App crashed, standing by for file changes to initiate restart

While I was in the middle of a nodejs course on Udemy, I encountered an issue where the code suddenly started breaking and throwing errors. Even after attempting to replicate the instructor's code, the problem persisted. I sought guidance from this a ...

How to use Sequelize to locate and update a record without a predefined model

I am currently facing a challenge with updating a database record using sequelize.js and mysql2. The issue is that I do not have access to the models folder or they have not been created yet. I have searched for solutions, but all of them mention using the ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

Calling this.$refs.upload.submit() is not providing the expected response from Element-UI

Currently working with element-ui and attempting to upload a file using the following code: this.$refs.upload.submit(); Is there a way to retrieve the response from this.$refs.upload.submit();? I have attempted the following: .then(response => { t ...

Issue displaying Windows_NT version 10.0.22621 along with the corresponding logs

NPM issues persisting I keep encountering problems with NPM not working properly, even after attempting npm install multiple times. It keeps generating an npm-debug.log file in another directory. The trouble started when I faced issues with reportwebvital ...

Guide on incorporating `Animate.css` into an Angular application

I've been attempting to implement the bounceInUp animation from animate.css on a div upon showing it, but I can't seem to get it to work. What am I doing wrong? Can someone guide me on the correct way to achieve this effect? This is my CSS code ...