Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

node.js - Why my API is blocking the request from my SPA even when the URL is in the allow origin?

I have a proxy server running in Node.js with Express hosted in Vercel and a SPA with React hosted in Netlify.

What I try to achieve is simple, make a request from my SPA in Netlify to my proxy in Vercel to register a user in MongoDB and than it returns me a id string in the route I try to hit.

The thing is this, in the proxy server I use the cors package to give access to a specific origin, in the dev test from my own machine I had been used the wild card * to allow any origin request and that's worked fine.

When I did upload the proxy in Vercel and my SPA in Netlify I did pass to my proxy the URL from my SPA to allow it but that didn't work and every time my SPA tries to hit my proxy it gives me the follow error in the Chrome console:

Access to XMLHttpRequest at 'https://myProxyServer.com/signin' from origin 'https://mySPA.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already tried to give to the origin option a regex based on my URL, a literal string and array with the possible origins but no one of the before options work, what I am doing wrong? What configuration should I use?

This is my current code in my proxy, index.js:

//MIDDLEWARES TO PREPARE THE REQUEST
app.use(cors({
    origin: 'https://mySPA.netlify.app',
    credentials: true,
}));
app.use(express.json());
app.use(cookieParser(config.cookieSecret));

//APP ROUTES
authServer(app);
apiServerRoute(app);

This is my code in my SPA:

if (validateFormData()) {
    const { password_repeat, ...userData } = formData;
    const resp = await axios.post(`${config.proxyUrl}/authserver/signin`, { ...userData }, { withCredentials: true });
    delete formData.password;
    setIsRegistered(true);
}
question from:https://stackoverflow.com/questions/65865553/why-my-api-is-blocking-the-request-from-my-spa-even-when-the-url-is-in-the-allow

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...