简体   繁体   中英

CORS blocking my node server from react app localhost

Tried everything I could find on here in regards to setting up cors for my node server. Tried aliasing my localhost and that doesn't seem to work either. Also tried using the CORS unblock extension.

error: localhost/:1 Access to fetch at 'http://localhost:8080/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. :8080/api/login:1 Failed to load resource: net::ERR_FAILED

im trying to use magic link authentication in my react app. I got this POST request being made to my node server

 const res = await fetch(`http://localhost:8080/api/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + didToken,
    },
  });

my server code is

const express = require("express");
const cors = require("cors");
const { Magic } = require('@magic-sdk/admin');
require('dotenv').config();
 
const app = express()
const magic = new Magic(process.env.MAGIC_SECRET_KEY);


app.use("*", (req, res) => res.status(404).json({ error: "not found" }));
// Allow requests from client-side
app.use(cors({origin: process.env.CLIENT_URL})); 

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );
  res.sendStatus(200);
  next();
});

app.post('api/login', async (req, res) => {
  console.log("login fired")
  try {
    const didToken = req.headers.authorization.substr(7);
    await magic.token.validate(didToken);
    res.status(200).json({ authenticated: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = app
app.use(cors({origin: process.env.CLIENT_URL})); 

I'd be curious what this URL is. If you want an open CORS policy you don't need to set anything any there.

Put a "/" in front of this route

app.post('/api/login', async (req, res) => {

I was able to reproduce your problem locally and this server setup worked for me to fix it.

const express = require("express");
const cors = require("cors");
const port = 8080;

const app = express();

app.use(cors());

app.post("/api/login", async (req, res) => {
  console.log("login fired");
  try {
    res.status(200).json({ authenticated: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

module.exports = app;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM