Graphql shield asks to enable cors on express server - express

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));

Related

get CORS problem when ty to get a token in keycloak with vuejs and axios

I trying to access one keycloak with axios in my vuejs app, but I receive the cors error, can someone help me please? (If I make a post from POSTMAN to my keycloak works fine)
I using this code:
const params = new URLSearchParams();
params.append("grant_type", "password");
params.append("client_id", "notas-front");
params.append("username", usuario.value);
params.append("password", password.value);
console.log(params);
const config = {
// withCredentials: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
axios.defaults.headers.common["Access-Control-Allow-Origin"] =
"http://localhost:8080";
axios
.post(
"http://localhost:8082/auth/realms/lumera/protocol/openid-connect/token",
params,
config
)
.then((response) => {
console.log(response);
});
and get this error:
but when I look the request I can't find the error:
the OPTIONS returns 200
but the POST dont
Postman doesn't care about Same Origin Policy, browser do. That's why your request is working in Postman but not in the browser.
Access-Control-Allow-Origin is a response header, you can't set it on the client request. And as you can see from the OPTIONS response headers your server is returning: Access-Control-Allow-Origin: http://localhost:8080
In a development environment the best way to solve this is setting a proxy in your vue configuration. Otherwise you should configure the server to allow requests from localhost:8080
Configure Web Origins properly in the Keycloak notas-front client config.

Cors issue solved by using proxy not working after served in Netlify Create-react-app

I have built a real estate site that makes a an api request to "https://completecriminalchecks.com" In development mode I was getting the dreaded blocked by Cors error. Through some research I found that I needed to use a proxy to solve the issue, which it did in development mode on my local host. But now I have deployed the site to netlify, I am getting a 404 error when making the request. when I look at the request from the network devtools its says
Request URL: https://master--jessehaven.netlify.app/api/json/?apikey=6s4xxxxx13xlvtphrnuge19&search=radius&miles=2&center=98144
I dont think this is right. How do i make netlify make the proper request to the api that was having cors issues in development?
Have you tried netify documentation about it?
Proxy to another service Just like you can rewrite paths like /* to
/index.html, you can also set up rules to let parts of your site proxy
to external services. Let's say you need to communicate from a
single-page app with an API on https://api.example.com that doesn't
support CORS requests. The following rule will let you use /api/ from
your JavaScript client:
/api/* https://api.example.com/:splat 200
Now all requests to /api/... will be proxied through to
https://api.example.com straight from our CDN servers without an
additional connection from the browser. If the API supports standard
HTTP caching mechanisms like ETags or Last-Modified headers, the
responses will even get cached by our CDN nodes.
You do not need to use a proxy, you enable CORRS in your server. Are you using a onde server?
If you use express something like this:
npm install --save cors
And then use it as middleware:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
Also in your netlify.toml file this will do the trick:
# The following redirect is intended for use with most SPAs that handle
# routing internally.
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
I also faced the same issue and solved by creating a netlify.toml file in root directory.
Here is a sample code for redirect which worked for me.
Place this inside the netlify.toml file.
Documentation guide for proxy :
[[redirects]]
from = "/api/users/tickets/"
to = "https://some-external-site.com/api/users/tickets/"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
[[redirects]]
from = "/api/users/cars/*"
to = "https://some-external-site.com/api/users/cars/:splat"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
I also faced the same issue , so I removed the "proxy" from the "package.json" file and created a variable to store the IP addess or URL for backend , then used it with the URL parameter for calling API. The CORS issue is solved in backend by allowing "All origins".
File to store base URL:
constant.js :
export const baseUrl = "https://backEndUrl";
File to call API:
getDataApi.js:
import { baseUrl } from "./constant";
export const getProfileData = () => (dispatch) => {
axios
.get(`${baseUrl }/api/profile`)
.then((res) =>
dispatch({
type: GET_PROFILE,
payload: res.data,
})
)
.catch((err) =>
dispatch({
type: GET_PROFILE,
payload: null,
})
);
};

How to solve CORS policy issue in a fullstack app [duplicate]

This question already has an answer here:
CORS Error: “requests are only supported for protocol schemes: http…” etc
(1 answer)
Closed 3 years ago.
I am building a MEVN-stack app, but I fail to make a request from my fron-end to the server due to Cross origin policies. I have enabled the cors middleware for all routes, but it does not take effect. I also tried applying it on each route individually and to specify the origin, but still no effect.
index.js:
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
const BanksController = require('./controllers/BanksController')
const OfficesController = require('./controllers/OfficesController')
const PORT = process.env.PORT || 3000
mongoose.connect(process.env.DB, { useNewUrlParser: true, useUnifiedTopology: true });
const app = express()
app.use(cors({ origin: 'http://localhost:3001' }))
app.get('/api/banks', BanksController.index)
app.get('/api/offices', OfficesController.index)
app.listen(PORT, () => console.log('Listening on port ' + PORT))
the ajax request:
axios.get('localhost:3000/api/banks')
.then(res => console.log(res))
.catch(err => console.log(err))
Try changing this:
axios.get('localhost:3000/api/banks')
to this:
axios.get('http://localhost:3000/api/banks')
Notice how the error message complains about the protocol scheme.
The problem is not your server. The problem is that using localhost:3000 treats localhost: as a scheme. The 'scheme' is the bit of the URL before the first colon.
You won't even see the request in the Network section of the developer tools because the browser doesn't know how to make a localhost: 'request'.
Try to add:
app.use(cors({ origin: 'http://localhost:3001/*' }))
It will be enabled for all routes. Or just use:
app.use(cors())
app.options('*', cors());

CORS not working on apollo-server-express

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.

CORS issues after deploying Express.js API to Heroku

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).