The CORS policy is preventing the AJAX request from functioning properly on localhost

Recently, I have been working on an Angular application that requires interaction with an API. To test it out, I set up an API on my localhost and made a request using AJAX. However, I encountered the dreaded CORS error. Despite trying various solutions found on StackOverflow, nothing seemed to work. The error message I kept getting was:

Access to XMLHttpRequest at 'localhost/graphql' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Can anyone provide guidance on how to resolve this issue?

Answer №1

In order to successfully access the site, you must ensure that both locations match in origin. The website is located at http://localhost:4200, but your attempt is targeting http://localhost.

To resolve this issue, include the port number so they align, for example, direct your request to http://localhost:4200/graphql

Alternatively, consider implementing CORS headers on your server.

Access-Control-Allow-Origin: http://localhost:4200

If you are using Express, you can easily achieve this by utilizing the cors middleware. Simply add the following line in your express server:

const cors = require("cors")  // npm i cors
app.use(cors())

For more information on CORS, visit MDN.

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

The complexity surrounding various versions of jQuery, the .noConflict method, and the jQuery migrate feature

I was tasked with making a large-scale website responsive, and decided to utilize Bootstrap as the framework. However, I encountered issues due to the jQuery version (v1.8.2) being used. In my development environment, I resolved this by including the follo ...

NodeJS/WebdriverJS: Error - 'Element is not connected to the webpage'

Hello there! I am new to WebDriver (chromedriver) and my knowledge of JavaScript syntax is quite basic, so please excuse me if my code appears messy. Currently, I have a clickAllElements(); function that identifies all elements within a class and performs ...

Extending the number of rows in an Angular mat-table beyond the size of the dataSource

Is there a way to display more rows of data in a mat-table than the length of the provided dataSource? For instance, consider the following sample data: people: [ { name: "John", birthday: "01.01.2000", hobbies: ...

Webpack creating a bundle file with no content

I'm currently facing a challenge with webpack/webpack-stream while trying to bundle some JavaScript files. The issue I am encountering is that, despite generating the bundle.js file, it turns out to be empty. To ensure clarity, I've provided the ...

Tips for integrating external JavaScript libraries and stylesheets into a widget

I am currently working on developing a custom Javascript widget that requires users to insert specific lines of code into their web pages. This code will then dynamically add an externally hosted javascript file, allowing me to inject HTML content onto the ...

Instructions on adding a class to the parent element when the child has a particular class

Here is the html structure I am working with: <section> <div class="v-middle"> <div class="row"> <h5 class="heading">Heading goes here</h5> </div> </div> </section> ...

Can custom HTML elements be designed to function similarly to standard ones?

What is the best way to create a custom HTML element that functions as a link without relying on inline Javascript? For instance: <x-button href="...">...</x-button> Can I develop an element like <x-button> that can accept an attribute ...

Can you explain how to incorporate the ternary operator in a jQuery script that is part of an

Working with core PHP, jQuery, and MySQL, I have implemented 2 dependent dropdowns in my project. The first dropdown for the company list is populated directly from the database using a query on the same page. For the second dropdown containing the employ ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

Using jQuery to make an AJAX call to an API

i have a request $(function(){ $.ajax({ type: 'GET', dataType:"jsonp", url: "http://localhost:8000/api/admin/announces", headers:{ 'Authorization' : 'Bearer eyJhbGci ...

Creating a Javascript function to turn lights off using CSS manipulation, similar to the feature found

Is there a way to use JavaScript to obscure all elements on a page except for one specific HTML element? This web application is optimized for Chrome, so CSS3 can also be utilized. ...

Using JavaScript, pass a single parameter to a function that accepts multiple arguments

Within my service, the Angular function is defined as follows: $delegate.isConfigurable = function (product, config) { if (product) { ///..... } return config.getDetail(); }; ...

I encountered an Angular error that is preventing me from updating and uploading images to my Firebase Storage because it is unable to locate the storage bucket

Hey there fellow developers! I'm currently working on a simple Angular app that allows users to upload images to a gallery. However, I've encountered an issue while trying to upload the images to Firebase Storage. I keep getting an error mentioni ...

Facing an issue with AngularJS where I am able to retrieve data.data, but struggling to assign it to a scope variable

Currently, I am developing a website using AngularJS that retrieves questions and multiple-choice answers from an Amazon Web Services table. This data is used to dynamically create a prelab questions page. The http get request is functioning properly; when ...

The JQuery ajax request is returning a 400 error code indicating a bad request

I've encountered a frustrating issue while using this JS code to send an ajax request: var data = JSON.stringify({ 'user_id': '<?=$user->id?>', 'package_id': '<?=$bundle->packa ...

Please replace the text with only letters and then submit it without any spaces, periods, commas, or other symbols

Whenever I encounter a form like this, I need to submit it and replace the text in the name field with only letters - no commas, spaces, or special characters. https://i.sstatic.net/9FQnT.png myform.html <script> function fixInput(event) { na ...

Mapping geographic coordinates with a null projection using D3

With d3.geo.path having a null projection due to TopoJSON already being projected, it can be displayed without any additional transformation. My goal is to plot data in the format of [longitude, latitude] on a map. Here is a simplified version of my code: ...

Steps to turn off sourcemaps in the @sentry/nextjs package

Currently, I am working on a Next.js project and have incorporated the @sentry/nextjs package for error logging purposes. My goal is to turn off sourcemaps in the client side of my deployed application. Despite going through this informative blog post fro ...

Altering the innerHTML of a <p> tag with a smooth transition

I am a beginner in the world of web design. I am currently working on a project where I need to continuously change the text inside a <p> element with a transition effect similar to a slideshow. Below is the code I have so far: <p id="qu">S ...