admin管理员组

文章数量:1319473

I created a react client app that request images from a node.js server app (V23.4.0), also created by me. It works fine locally but when I upload the server to netlify, each request made is blocked by the CORS policy.

I created simplified versions of both apps and start testing different solutions from this site.

App.jsx (client)

function App() {

    useEffect(() => {
        getServerResponse();
    });

    const getServerResponse = () => {
        axios.get("/lify/functions/app:4000/test-response",
            {
                params: {
                    mytext: "Alexis response"
                }
            })
            .then(response => {
                if (response.status = 200) {
                    console.log(response.data);
                }
            })
            .catch((err) => {
                alert("GET ERROR: " + err);
            });
    }

    return (
        <div className="App" />
    );
}

app.js (server)

const express = require('express');
const serverless = require("serverless-http");
const cors = require("cors");
const app = express();
const router = express.Router();

app.use("/.chambaserver/functions/app", router);
module.exports.handler = serverless(app);

app.use(express.static(__dirname + '../..'));

//Local client site (App.jsx)
const corsOrigin = 'http://localhost:5173';

//Use CORS package
app.use(cors({
    origin: [corsOrigin],
    methods: ['GET', 'POST'],
    credentials: true
}));

app.get('/test-response', (req, res) => {
    let myText = req.query.mytext;
    console.log(myText);
    return res.send("This is your message: " + myText);
});

//Start in port 4000
const port = 4000;
app.listen(port, process.env.IP, function () {
    console.log(`Server is running on port ${port}`);
});

I already tried:

  1. Using cors npm package (as you can see in code). I tried write it with and without options (just "app.use(cors())"), but the answer is the same.
  2. Adding the CORS header in .toml file. It changes the message to an error 404: not found.
  3. Add options to the page, with the below code, but the result is the same (CORS block the connection)
app.options('/test-response', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.end();

Can you tell me what I am doing wrong? By the way, I keep the server deployed in netlify, with solutions 1 and 3, so feel free to test making an axios call (the link is '/lify/functions/app:4000/test-response').

I created a react client app that request images from a node.js server app (V23.4.0), also created by me. It works fine locally but when I upload the server to netlify, each request made is blocked by the CORS policy.

I created simplified versions of both apps and start testing different solutions from this site.

App.jsx (client)

function App() {

    useEffect(() => {
        getServerResponse();
    });

    const getServerResponse = () => {
        axios.get("https://chambaserverlify.app/lify/functions/app:4000/test-response",
            {
                params: {
                    mytext: "Alexis response"
                }
            })
            .then(response => {
                if (response.status = 200) {
                    console.log(response.data);
                }
            })
            .catch((err) => {
                alert("GET ERROR: " + err);
            });
    }

    return (
        <div className="App" />
    );
}

app.js (server)

const express = require('express');
const serverless = require("serverless-http");
const cors = require("cors");
const app = express();
const router = express.Router();

app.use("/.chambaserver/functions/app", router);
module.exports.handler = serverless(app);

app.use(express.static(__dirname + '../..'));

//Local client site (App.jsx)
const corsOrigin = 'http://localhost:5173';

//Use CORS package
app.use(cors({
    origin: [corsOrigin],
    methods: ['GET', 'POST'],
    credentials: true
}));

app.get('/test-response', (req, res) => {
    let myText = req.query.mytext;
    console.log(myText);
    return res.send("This is your message: " + myText);
});

//Start in port 4000
const port = 4000;
app.listen(port, process.env.IP, function () {
    console.log(`Server is running on port ${port}`);
});

I already tried:

  1. Using cors npm package (as you can see in code). I tried write it with and without options (just "app.use(cors())"), but the answer is the same.
  2. Adding the CORS header in .toml file. It changes the message to an error 404: not found.
  3. Add options to the page, with the below code, but the result is the same (CORS block the connection)
app.options('/test-response', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.end();

Can you tell me what I am doing wrong? By the way, I keep the server deployed in netlify, with solutions 1 and 3, so feel free to test making an axios call (the link is 'https://chambaserverlify.app/lify/functions/app:4000/test-response').

Share Improve this question edited Jan 20 at 0:21 Phil 165k25 gold badges262 silver badges267 bronze badges asked Jan 19 at 20:01 Alexis MercadoAlexis Mercado 237 bronze badges 4
  • 1 The link to your test function gives me a 404. Seems like solution 2 actually works as expected then. – mwopitz Commented Jan 19 at 20:55
  • Sorry. I didn't test the link directly. Instead I check what response returns when I make a request from with axios and given the CORS error and the fact that it worked in development, I assumed that the problem where in the policy. So, excuse the question. The link should return something on its own? – Alexis Mercado Commented Jan 19 at 22:47
  • 1 Have you read this page? You seem to be missing the [[redirects]] configuration required to get Express to match request URLs to routes – Phil Commented Jan 20 at 0:18
  • @Phil I will try it. Thanks – Alexis Mercado Commented Jan 20 at 1:23
Add a comment  | 

1 Answer 1

Reset to default 2

The request you're sending isn't being handled by anything so it returns a 404 without any of the necessary Access-Control-Allow-* headers.

As per the Netlify docs, you need to configure internal redirects for Express to match requests to your configured routes.

Eg, in netlify.toml

[functions]
  external_node_modules = ["express"]
  node_bundler = "esbuild"
[[redirects]]
  force = true
  from = "/api/*"
  status = 200
  to = "/lify/functions/api/:splat"

Then configure your Express routes to match the /api prefix. This is most easily done using a Router though you can also simply include the prefix in your handler paths

app.get('/api/test-response', (req, res) => {
  let myText = req.query.mytext;
  console.log(myText);
  return res.send("This is your message: " + myText);
});

Your client-side request would then use something like this

axios.get("https://chambaserverlify.app/api/test-response", {
  params: {
    mytext: "Alexis response",
  },
})

Also, make sure you register the cors() middleware before any routes you want made available cross-origin.

本文标签: nodejsHow to stop CORS from blocking connections to my node netlify serverStack Overflow