What could be causing the CORS policy to block GET requests?

In my recent project, I have been developing a hybrid app that utilizes express and cors. This application is responsible for sending both get and post requests from a client JavaScript file to a server file. Everything was functioning smoothly until I started adding final touches, and encountered an error while making a get request:

Access to XMLHttpRequest at 'http://address:3000/search/Cottonelle' from origin 'http://localhost:8000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://address.com' that is not equal to the supplied origin.

The "address" mentioned refers to the machine's IP address. Users of this app can input various items and send them to the server for storage, as well as retrieve saved entries. Initially, using 'http://localhost' instead of the actual IP address worked fine. Further testing revealed that altering the connect-src in the HTML's Content Security Policy (CSP) along with using the IP address in the client JS file made it functional, indicating an issue with the server-side JS file. Interestingly, post requests are successful whereas get requests fail. The main distinction between these requests is that post uses '/post' as its route while get employs '/search/:query'.

Here's the minimal code required to replicate the problem:

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com
        ;connect-src http://address:3000">

        <script src="jquery.js"></script>
        <script src="client.js"></script>
    </head> 
<body>
</body>
</html>

Client.js:

const address = "http://address:3000" 

let name = "test"
$.get(address + "/search/" + name ,function(data, status){
    alert("The status text is: " + status + "\nThe status code is: " + data);
});

Server.js:

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

var corsOptions = { origin: 'http://address.com', optionsSuccessStatus: 200}
app.use(cors(corsOptions))
const port = 3000

app.get('/search/:query', (req, res) => {
    let myStatus = res.statusCode;
    res.sendStatus(myStatus)
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

Answer №1

the server.js approved but not localhost:8000 (it seems like your website is running locally)

to fix this problem, include localhost:8000 in the authorized host list of server.js

app.use(cors(
   { origin: 'http://address.com', optionsSuccessStatus: 200},
   { origin: 'http://localhost:8000', optionsSuccessStatus: 200}
))

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

Adjust the width of a div within a nested iframe using jQuery without the need for an identifying ID on the iframe itself

Below is the code sample I'm working with: <iframe> <div id="inner_div"> Here's some text! </div> </iframe> I am aware that by adding an id to the iframe, I could follow the instructions provided here to access t ...

Displaying a picture solely in a designated region

I created a basic menu using an unordered list: <ul class="courses"> <a href="#"> <li class="spinny"> <h3>Course Title</h3> <img class="rotateme" src="images/logo_transparent.png"/> </li& ...

Is a non-traditional fading effect possible with scrolling?

I have implemented a code snippet to adjust the opacity of an element based on scrolling: $(window).scroll(function () { this = myfadingdiv var height = $(this).height(); var offset = $(this).offset().top; var opacity = (height - homeTop + ...

Displaying elapsed time in JavaScript (Node.js)

Looking for a way to convert a date time or time-stamp format like 2015-12-18 07:10:54 into a relative time, such as "2 hours ago." I attempted the code provided, but it seems to consistently show an incorrect estimation of "8 days ago." function convert ...

What is the best way to transfer a picture from the express server to the client (using React)?

I am faced with the challenge of displaying an image in React that is not a local client image or an external image from the web, but rather an image located on the Node.js Express server. I want to avoid treating it as an external image due to potential d ...

leveraging the situation and a clever opening

Currently, I'm diving into mastering the proper utilization of context and hooks. Initially, everything worked flawlessly while all components remained within a single class. However, troubles arose when I segregated them into multiple classes leading ...

Error importing React Icons with the specific icon FiMoreHorizontal

Currently following a guide to create a Twitter-like application and I need to add the following imports: import { FiMoreHorizontal } from 'react-icons/fi' 2.3K (gzipped: 1K) import { VscTwitter } from 'react-icons/vsc' 3.1K (gzipped: ...

Having trouble accessing PDF files on Electron framework

Despite following the advice provided in similar questions' answers, such as including webPreferences: { plugins: true } in the options when creating a BrowserWindow instance, I am still encountering issues. Every attempt to open or view a PDF ...

How can a JQuery slideshow be programmed to only iterate once?

Looking to create a slideshow that transitions between images every two seconds? Check out the code snippet below: HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

Node.js app on Google App Engine experiencing memory leaks when running a basic pubsub application, leading to surpassing the soft private memory limit

My experience with developing a simple appEngine using pubsub app has led me to some concerning observations. Upon reviewing the appEngine logs, I noticed a constant increase and drop in memory usage that repeats itself. Upon closer inspection of the logs, ...

Should case sensitivity be disregarded in an array's input?

I need to search for a value in an array, but the search should be case-insensitive. How can I achieve this? This is the code snippet I am using: $.ajax({ type: "GET", url: "ajax.php", dataType: "json", data: { pageType: pageType, input: request.term, da ...

react native is not updating the view even though the state has been changed

Upon opening my component, I am looking to retrieve Assets from a Media Folder (which is currently functional) and then pass them along to another component. However, the issue arises when launching the app for the first time, as the "listOfAssets" state a ...

Issue Occurs when Updating Data in Node.js with MongoDB: Patch Method Returns Success but No Changes Reflect in Database

Recently, I've been attempting to make changes to my "Orders" by updating the product, quantity, and _id fields. However, even after running the patch command, it seems like nothing actually gets updated. Check out my API Update code screenshot here. ...

Using ngFor results in duplicate instances of ng-template

I'm facing a challenge with the ngFor directive and I'm struggling to find a solution: <ng-container *ngIf="user.images.length > 0"> <div *ngFor="let image of images"> <img *ngIf="i ...

jQuery append allows for the addition of multiple items simultaneously

I need assistance with automatically creating a div when clicking on a button. I'm encountering an issue where each click increments the display of the div. Can you provide some guidance on how to resolve this problem? ...

How can we use JavaScript to add a class to the <html> element?

What is the method to apply a class to the root element <html> in JavaScript? ...

Error Type Not Caught on Console

Could you please help me understand the error message below? I'm not very familiar with JavaScript. Uncaught TypeError: $(...).sss is not a function at HTMLDocument.<anonymous> (codejs.js:3) at i (jquery.min.js:2) at Object.fireWith [as resolve ...

When using React, I have successfully saved my data in LocalStorage using JSON, but I am facing issues retrieving it upon reloading the page

After successfully converting the data item into JSON format, I faced an issue where upon reload, the item would reload but always ended up being rewritten. This led to a red line appearing under the (localStorage.getItem('chatLInes')) part accom ...

Efficiently incorporating multiple properties into one in Angular

Within my Angular service, I have defined variables in the following manner: export class MyService { someVariableA = 1; someParams = { someVariableB, otherVariable: this.someVariableA }; } In a component, I update 'someVariableA&a ...