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}`)
})