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:
- 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.
- Adding the CORS header in .toml file. It changes the message to an error 404: not found.
- 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:
- 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.
- Adding the CORS header in .toml file. It changes the message to an error 404: not found.
- 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 Answer
Reset to default 2The 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
版权声明:本文标题:node.js - How to stop CORS from blocking connections to my node netlify server? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742060508a2418554.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
[[redirects]]
configuration required to get Express to match request URLs to routes – Phil Commented Jan 20 at 0:18