How to allow access to a NextJS api route from a different domain? - next.js

I have a NextJs with an /api/revalidate route for on-demand cache revalidation.
But I need to call this endpoint from a different domain and I'm getting the following error:
Access to XMLHttpRequest at 'DOMAIN_1/api/revalidate' from origin 'DOMAIN_2' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
How can I set up CORS on an API endpoint for a NextJS app?

Just found out that NextJS has an example about setting up CORS in an API route:
https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors
And also you can use nextjs-cors, which is a wrapper on top of cors:
https://www.npmjs.com/package/nextjs-cors
The code will look something like this:
import NextCors from 'nextjs-cors';
async function handler(req, res) {
// Run the cors middleware
// nextjs-cors uses the cors package, so we invite you to check the documentation https://github.com/expressjs/cors
await NextCors(req, res, {
// Options
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
origin: '*',
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
});
// Rest of the API logic
res.json({ message: 'Hello NextJs Cors!' });
}

Related

Angular 12 with .NET and Windows Domain Authentication

So I've trying to setup Angular login with Windows Domain Authentication and the backend is hosted with .NET.
Every resource about that on the internet suggest adding interceptor on Angular side:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({ withCredentials: true });
return next.handle(req);
}
and registering it in app.module
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: CredentialsInterceptor, multi: true}
],
then a sample http request in a service
this.http.get(this.baseUrl + 'user')
But making a request
returns 500 with cors policy error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
And what is strange, necessary cors headers have been already added on backend. Since I'm working on frontend only, is there anything that could be added on Angular side?
What I'm expecting is a Windows Domain login window showing after making an http request.
Any help will be appreciated

Access to fetch has been blocked by CORS policy at Firebase Functions API

I'm working on my project which includes Angular 9 application using firebase functions. I deployed some function, which should update some values on the Firebase Realtime Database. Unfortunately, I encountered a problem with CORS policy if I use my API.
After adding middleware to my express server, where I added these code, the problem still occurs.
app.post('/changeQuantity', permit(), (request: any, response: any) => {
response.status(200).send({ data: { Message: 'Changing order quantity - success.' } });
})
export default function permit() {
return (req: any, _res: any, next: any) => {
_res.setHeader('Access-Control-Allow-Origin', '*');
_res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
next();
};
}
I noticed, that I get this error when frequently requesting API.
Here is the error which server returns:
Access to fetch at [here is a link to my API endpoint] from origin [my origin] has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Did anybody have the same issues with the firebase functions API? Could it be related to frequent requests of my API endpoints from the development environment? Thanks in advance.
Try using response.header to set the CORS properties, like this
app.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
next();
});

CORS error when making Axios calls to Cloudrun service from Firebase hosted app

This looks to be pretty obvious but I've been trying to figure it out for a couple of days now and still can't get it to work. Please, can someone point out what I'm missing.
I'm trying to make an axios call to my cloud run service from my firebase hosted SPA. To isolate the issue I followed the steps outlined in the [firebase tutorial for cloud run] (https://firebase.google.com/docs/hosting/cloud-run#node.js)
Step 4 of the tutorial talks about setting up rewrite to use the firebase domain as a proxy to your cloud run service. It says that the helloworld service would be reachable via
Your Firebase subdomains:
projectID.web.app/helloworld and projectID.firebaseapp.com/helloworld
So I follow the steps and deploy the service. Then I try to make an axios call to the service from the SPA like below
testHelloWorld () {
axios.get(`https://myProjectId.firebaseapp.com/helloworld`)
.then((data) => {
console.log(data)
})
.catch(ex => {
console.error(ex)
})
})
}
But then I get the CORS error
Access to XMLHttpRequest at 'https://myProjectId.firebaseapp.com/helloworld' from origin 'https://myFirabaseApp.firebaseapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This answer states that this should be possible so I'm not sure what I'm doing wrong.
N.B:
While debugging, I updated the node app from the tutorial to add cors support like below. Still didnt work.
const express = require('express');
const app = express();
const cors = require('cors'); //Imported and added this
app.use(cors()); // Used here
app.get('/', (req, res) => {
console.log('Hello world received a request.');
const target = process.env.TARGET || 'World';
res.send(`Hello ${target}!`);
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log('Hello world listening on port', port);
});
So the question here is, how do I make an Axios/AJAX call to my cloud run service using the firebase rewrite rule?
Please check if you have installed cors: npm install cors.
Please check if the 2 following options can solve your issue:
1= Use the following code :
app.use(cors({origin:true,credentials: true}));
2) If the previous didn't work, please use the following code:
app.get('/', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
console.log('Hello world received a request.');
}
Please let me know if it works for you.

Axios network error on Cors Post request with status code 200

I use axios to communicate with my own API (not written in NodeJS).
When I post a non simple request axios always goes directly to the catch block displaying a network error in the console, even with 2 successful Http Requests.
Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:1634:15
handleError#http://localhost:3000/static/js/bundle.js:1170:14
There is also a CORS warning about a missing header
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
However it is included in the Options Request!
When I add 'Access-Control-Allow-Origin': '*' in the Axios request headers, the warning is gone, but the browser doesn't fire a Post request after the successful Options request.
For the sake of being complete here are the post request headers.
The code:
postForm = () => {
axios.post("http://127.0.0.1:8080/",
myComplexObj, {
headers: {
//'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
timeout: 15000
}
).then(res => {
console.log(res);
alert('success');
})
.catch(function(error) {
//code always end up here
console.log(error);
/*Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:1634:15
handleError#http://localhost:3000/static/js/bundle.js:1170:14
*/
console.log(error.response); //undefined
console.log(error.response.data); //undefined
}
})
Any help is gladly appreciated.
What I have tried:
Remove the timeout //no change
Remove the Catch block //still no success
Return status code 204 on Options and/or Post requests //no difference
You are confusing because status 200, however, the browser will not allow you to access the response of a CORS request if the Access-Control-Allow-Origin header is missing.
Here are some great articles that explain how CORS works:
https://www.html5rocks.com/en/tutorials/cors/
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Anyway, I think that you are using Django. So, you need add to settings.py:
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
'localhost'
)
Or wherever you have the axios code.

Angular2 CORS issue

I'm new to angular2 and to be fair I have very few knowledges which I try to fix, however I've run into some issues about cross site request, trying to access a service from another application but I have this issue whatever I try to do
XMLHttpRequest cannot load https://hr/Team/EditEmployeeInfo.aspx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54396' is therefore not allowed access. The response had HTTP status code 401.
This is my angular2 service and I've tried something like this
getUserHrtbProfile(userId): Promise<any> {
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET, PUT, POST, DELET');
headers.append('Access-Control-Allow-Origin', '*');
var apiUri: string = "https://hrtb/Team/EditEmployeeInfo.aspx?emplid={0}&Menu=InfoEmployee&T=0".replace("{0}", userId);
return this.http.get(apiUri, headers).map(result => result.json()).toPromise();
}
and this is my component
this.bannerService.getUserHrtbProfile(this.userId).then(hrtbJson => {
this.hasHrtbAccess = hrtbJson.HasHrtbAccess;
this.hrtbProfileUrl = hrtbJson.HrtbProfileUrl;
}).catch(err => {
this.hasHrtbAccess = false;
});
I've search a solution on my problem but still could not find one that suits my need.
Angular 2 http request with Access-Control-Allow-Origin set to *
But most important, is this an angular2 problem that I need to solve? Or in fact as I've read it should have been handled by the team that exposes the API?
Thank you all.
You need to enable CORS on your API backend.
Only for testing purpose you could use this Chrome Extension to simulate CORS on your api backend:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
You are trying to make request on other domain, this is what you can not resolve here. try with making request at you backed code, this will resolve you issue.

Resources