#CORS error even though I'm using the cors middleware?

9 messages · Page 1 of 1 (latest)

unreal junco
#

I'm using Express on the backend and I have app.use(cors());. It is running on localhost:3000.
I have Angular on the frontend running on localhost:4200.
Trying to send a GET request I get a CORS error: Access to XMLHttpRequest at 'localhost:3000/api/state' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: chrome, chrome-extension, chrome-untrusted, data, http, https, isolated-app.

I must be missing something obvious, but I cannot figure it out.

#

My full app.ts:

import express from "express";

import { Game } from "./game/game.js";


const app = express();

app.use(cors());
app.use(express.json());
app.use(express.static("public"));

// app.use((req, res, next) => {
//     res.setHeader("Access-Control-Allow-Origin", "*");  
//     res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS");
//     res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//     next();
// });

app.get("/", (req, res) => {
    res.send("Hello, World!");
});

const game = new Game();

app.post("/api/addone", (req, res) => {
    console.log("GET /api/addone");
    game.addOne();
    res.json(game.getJson());
});

app.post("/api/reset", (req, res) => {
    console.log("GET /api/reset");
    game.resetCounter();
    res.json(game.getJson());
});

app.get("/api/state", (req, res) => {
    console.log("GET /api/state");
    res.json(game.getJson());
});

const port = 3000;

app.listen(port, () => {
    console.log("Server is running on port " + port);
});
odd fog
#

Stack overflow is suggesting that it's the missing http:// prefix.

#

Though TBH, rather than configuring your app to allow CORS from everywhere (which can be a security issue) its common to solve this via a proxy built into your dev server.

#

So you'd write your API requests like fetch("/api/state"), and in development that would hit localhost:4200/api/state and your dev server would proxy that request to your localhost:3000/api/state (which avoids the CORS issue because the request isn't happening in a browser).

#

And in production probably your UI and your API are running in the same origin and fetch("/api/state") just does the right thing, anyway.

unreal junco
#

Yeah, that was it. Obvious in hindsight.

#

As for the rest, I'm going to think about deployment details much later. Right now, this is for development, and I'd like to have the frontend and backend separate.