Package: apollo-server-express
Version: v2.6.0
Issue: CORS settings aren't taking effect.
Reported to Apollo?: Yes, Issue 3058
Description: From our react client, we started sending apollographql-client-name & apollographql-client-version headers for better client awareness in Apollo Engine.
Access to fetch at 'https://something.com/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field apollographql-client-name is not allowed by Access-Control-Allow-Headers in preflight response.
We receive above CORS error. We enabled cors on Apollo Server through express middleware by passing cors: true. For some reason, this changes are not making any difference. We continue to receive above error.
const server: ApolloServer = new ApolloServer({
...
...
});
const app: Application = express();
server.applyMiddleware({
app,
cors: true,
path: '/graphql',
});
We have nginx sitting in front and it does receive request and forwards to Apollo Server.
cors: true enables everything by default?
We tried being very specific but that didn't help either.
cors: {
origin: true,
allowedHeaders: ['Authorization', 'Content-Type', 'apollographql-client-name']
},
Any inputs and suggestions are welcome!
Issue is resolved.
We had kubernetes ingress layer on top of our Apollo Server and that's what was causing changes not to reflect. After we enabled cors on nginx ingress, we were able to make successful calls.
Related
I installed graphql shield and using it with Apollo graphql. Since I use shield, I get an error regarding cors every time I execute a mutation. I am not sure why this happens as I am calling the Api just as before from my own server. I also tried to enable cors on my Node.js server but still some cross origin error occurs.
const cors = require('cors');
app.use(cors())
Try This one!
const cors = require('cors')
const corsOptions = {
origin: 'http://localhost:4200',
credentials: true,
}
app.use(cors(corsOptions));
I have the following CDK code for my API Gateway
this.restAPI = new RestApi(this, name, {
cloudWatchRole: true,
domainName: {
domainName: props.recordName,
certificate: props.cert,
endpointType: EndpointType.REGIONAL,
securityPolicy: SecurityPolicy.TLS_1_2
},
defaultCorsPreflightOptions: {
allowOrigins: Cors.ALL_ORIGINS,
allowMethods: ['OPTIONS', 'POST', 'GET', 'DELETE', 'PUT', 'PATCH'],
allowHeaders: Cors.DEFAULT_HEADERS,
maxAge: Duration.seconds(86400)
}
});
which results in this
But I'm still running into this error:
/#/actors:1 Access to fetch at 'https://web-api.alpha.myapp.com/api/v1/actors?page=1' from origin 'https://alpha.myapp.com' has been blocked by CORS policy: 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.
But if you look at my Access-Control-Allow-Origin it's set to '*'. So I'm not sure what I'm missing.
And just to validate I do have Lambda Proxy integration turned on
Apparently my lambda that returns the GET content actually has to include the relevant CORS headers. It's not enough to just turn on CORS support on API Gateway.
I have a user authentication server setup using Express and Node.js in my localhost Port 3333 and I am trying to connect to the endpoint in Next.js port 3000 using isomorphic-unfetch for the fetch. I am getting a CORS 401 error, I have done a fair bit of research already but just wanted to know whether it was possible connecting to a Express server on localhosts? I have tried adding "Access-Control-Allow-Origin": "*", "Content-Type": "multipart/form-data" to a header object. The express server has cors setup already.
This function below is called on click of a button.
onLoginClick = async () => {
let header = new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
});
const res = await fetch("http://localhost:3333", {
method: "POST",
header,
body: JSON.stringify({
username: "USER",
password: "PASSWORD"
})
});
}
Error message -
http://localhost:3333/ 401 (Unauthorized)
Response {type: "cors", url: "http://localhost:3333/", redirected: false, status: 401, ok: false, …}
First of all, CORS is configured on the server side. You configure your server to allow calls from specific origins.
In your code, onLoginClick is a client-side code, it runs on the browser, client cannot decide which origin the server should allowed to, that would defeat the purpose of having CORS.
Usually you don't need to change the cors configuration in a Next.js app, because you would be calling the API from the same origin that hosted the client side app.
By default, Next.js only support same-origin for API Routes, if you need to customize it, you can use micro-cors.
I am trying to get CORS working on my AWS Lambda server using Serverless. Right now I have two sub-domains (api.site.co and app.site.co).
In my app.js file on Express, I have installed CORS and enabled it like such:
app.use(
cors({
origin: 'https://app.site.co',
optionsSuccessStatus: 200,
}),
);
app.options('*', cors());
And then using the Axios module in React, I make this call:
axios
.post('/users/register', user)
.then(res => history.push('/login'))
.catch((err) => {
dispatch({
type: GET_ERRORS,
error: err.response.data,
});
});
Also, in my app.js file for the client app:
axios.defaults.baseURL = 'https://api.site.co';
When submitting any request, I receive this error:
Access to XMLHttpRequest at 'https://api.site.co/users/register' from origin 'https://app.site.co' 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.
So, far I have also tried changing my CORS configuration to:
app.use(cors());
app.options('*', cors());
But I am still getting the same error.
Any suggestions on how to address this?
Looks like there is a typo:
https://app.site.co/users/register => https://api.site.co/users/register
You're making a request to https://api.site.co but your configuration specifies https://app.site.co
This was a problem with the AWS Lambda Serverless setup. I needed to add
functions:
app:
handler: app.handler
events:
- http:
path: /
method: any
cors:
origin: 'https://app.site.co'
- http:
path: '{proxy+}'
method: any
cors:
origin: 'https://app.site.co'
So that it would allow CORS requests when proxying to the Express middleware.
I've tried everything I could find on CORS issues, but I can't seem to solve it. I'm using a React.js app with Express.js API to handle the mailer function. When running it locally I did get CORS issues and solved it like this:
const cors = require('cors')
app
.use(cors())
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(mailer)
I deployed React app and Express API to Heroku, and suddenly started getting CORS errors again:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://...' is therefore not allowed access. The response had HTTP status code 503.
So I tried several different ways to make it work but none of it helps, some examples:
app
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'https://florismeininger.herokuapp.com');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
.use(mailer)
app
.use(cors({origin: 'https://florismeininger.herokuapp.com'}))
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(mailer)
app
.use(cors({origin: '*'}))
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(mailer)
So it was a 503 error in response to a preflight OPTIONS request.
I worked around sending this request by using multipart/form-data and attaching the body:
var data = new FormData()
data.append('body',body)
api.post('/mailer', { attach: body })
Now I'm getting a new POST 503 error and also this error:
Failed to load https://florismeininger-mailer-api.herokuapp.com/mailer: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://florismeininger.herokuapp.com' is therefore not allowed access. The response had HTTP status code 503. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I tried using the 'no-cors' mode also but didn't work. Keep getting the No 'Access-Control-Allow-Origin' header is present error.
If you are getting the 503 in response to a CORS preflight OPTIONS request, then as #sideshowbarker comments, the problem is that the OPTIONS request method probably isn't allowed by your web server (Apache or whatever).