Enabling cross-origin requests using Express JS and the power of HTML5's fetch()

How do I enable cross domain requests using ExpressJS server and Javascript's fetch? It seems like there might be an issue with the client-side fetch() function because the response headers include Access-Control-Allow-Origin: *.

I attempted to resolve this by adding the following code, but it has not solved the problem:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "localhost:4200"); // update this to match the requesting domain
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

Upon inspection, it appears that the request headers do not contain any information related to CORS:

Accept  
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding 
gzip, deflate
Accept-Language 
en-US,en;q=0.5
Cache-Control   
max-age=0
Connection  
keep-alive
Host    
localhost:4200
If-None-Match   
W/"2ef-TFWfb4ktmG8ds+qhoRRzEvmkPdY"
Upgrade-Insecure-Requests   
1
User-Agent  
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/68.0

The frontend code snippet:

export function createHttpObservable(url: string) {

    return Observable.create(observer => {

      fetch(url, {mode: 'cors'})
        .then(response => {
          return response.json();
        })
        .then(body => {
          observer.next(body);
          observer.complete();
        })
        .catch(error => {
          observer.error(error);
        })

      });

  }

Error message received:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9000/api/courses. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Answer №2

The URL for the localhost is incorrect. Please modify it as shown below.

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // update to match the domain you will be requesting from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();

});

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

utilize text offsets to insert tags within strings

I've been facing challenges with using JavaScript string methods and regular expressions. It seems like I might be missing something obvious here. Please forgive me if I'm repeating the question asked by tofutim in more detail, which can be found ...

Steps to successfully implement onClick functionality in html within C# server side code

I'm having trouble with my onClick function. When I click, nothing happens and there are no errors to help me diagnose the issue. var data = new FormData(); data.append("cart_list", new_cart); $.ajax({ url: "@Url.Action ...

A guide on sending multiple input values using the same class name or id through ajax

My goal is to send multiple input values through AJAX to my PHP script. Everything works smoothly when I use getElementById. However, I have the functionality to add a child. The issue arises when it only retrieves values from the first child while iterati ...

When utilizing the tab key on Chrome, the iFrame fails to scroll

We are currently facing an issue with our web application that is embedded inside an iFrame. On one of our HTML pages, there are numerous textboxes with a large amount of content, requiring users to scroll down to navigate through it all. When using the ...

What is the best way to interpret the JavaScript code within a Vue/Quasar project?

Sample Code: <script type="text/javascript" src="https://widget.example.com/widgets/<example_id>.js" async defer></script> I am looking to integrate this code into Quasar Framework and utilize it with Vue.js. Do you have any suggesti ...

How to arrange elements at the same level in Node.js using sequelize-hierarchy?

Is there a way to change the order of items on the same level in sequelize-hierarchy for creating a menu? I've noticed that currently, the items are ordered by their sequence of insertion. But what if I want to manually set the order? Here is an exam ...

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...

Troubleshooting the issue of jQuery Ajax failing to deliver a PDF

I have been attempting to use jquery, ajax, and django to download a pdf file. Here is my code from the views.py file in Django: if request.POST.get('action') == 'download_labels': order_list = json.loads(request.POST. ...

The default value of components in Next.js

I'm working on establishing a global variable that all components are initially rendered with and setting the default value, but I'm unsure about how to accomplish the second part. Currently, this is what I have in my _app.tsx: import { AppProps ...

Are extra parameters in the URL causing issues with AngularJS routing?

When I receive password reset instructions in my app, the URL I use to go to the server looks like this: /changepass?key=1231231231212312 In the controller, I have the following code: if (typeof $routeParams.key !== 'undefined') { $scope ...

Leverage variable as an expression when utilizing ng-include

Here is an example of working code: <div ng-include src="'Test.html'"></div> However, this code does not work: <div ng-include src="ctrl.URL"></div> (When ctrl.URL is set to "Test.html"). I have also tried setting it t ...

Ways to modify Angular pipe without specifying data types

I am in the process of extracting an Angular pipe from an application to a library. The current pipe is tied to specific types, but I want to change it to use generic types while maintaining type safety. Original Pipe: import { Pipe, PipeTransform } fr ...

Creating a method in Angular that combines async/await functionality with Observables

After transitioning from using async/await to Observables in Angular, I am trying to refactor the following code snippet to make it work with Observables: async refreshToken() { const headers = this.authStorage.getRequestHeader(); const body = { ...

Tips on efficiently reusing a variable

As someone who is relatively new to Jquery and Javascript, I have been attempting to search for a solution to my question on this platform. However, it seems that the terminology I am using may not be accurate enough to yield relevant results. If there is ...

Optimizing jQuery scripts by consolidating them to reduce file size

I've created a jQuery script that performs the same task but triggers on different events, including: Page load Dropdown selection change Clicking the swap button Typing in a text field However, I had to write separate scripts for each of these eve ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfully created the AJAX call and ...

The array within the JSON object holds vital information [Typescript]

I have some data stored in an Excel file that I want to import into my database. The first step was exporting the file as a CSV and then parsing it into a JSON object. fname,lname,phone Terry,Doe,[123456789] Jane,Doe,[123456788, 123456787] Upon convertin ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

fetching numerous JSON documents using jquery

I am struggling to retrieve data from multiple JSON files and display it in a table. Despite being successful in appending data from one JSON file, I encountered issues when trying to pull data from multiple files. Here is my code: var uri = 'sharepo ...

Why do I keep receiving the error message "Cannot set property of undefined"?

In the midst of a small project that involves utilizing nuxt, js, and axios, I encountered an issue when attempting to assign the response data to my formFields object. Despite having declared formFields within the data section, I kept receiving an error m ...