11

NodeJS Express platform. Using Zeit Now 2. Cannot use server.js as proxy to send from backend to prevent CORS. So, nor wrestling with CORS problems. Tested desktop: chrome, safari, firefox. Mobile: chrome, firefox. Have tested to host on Now with HTTPS, same error as I get locally on both localhost:3000 and 127.0.0.1:3000, same using port 80.

Access to fetch at 'https://**MY_URL**/user/login' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I use https://www.npmjs.com/package/cors to set my CORS configs:

app.use(cors({
  'allowedHeaders': ['Content-Type', 'API-Key', 'API-Secret', 'Access-Control-Allow-Headers'', 'accept', 'client-security-token'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS',
  'preflightContinue': false,
  'credentials': true
}));

The CORS settings doesn't seem to work for my, so I tried with the now.json file, like this (trimmed veersion):

{
  "name": "my-test-api",
  "version": 2,
  "routes": [
    {
     "src": "/.*",
     "methods": ["GET", "POST", "OPTIONS"],
     "headers": { "Access-Control-Max-Age": "1000", "Access-Control-Allow-Methods": "GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS", "Access-Control-Allow-Origin": "*", "Accept": "text/plain", "Content-Type": "text/plain", "Access-Control-Allow-Headers": "sessionId, Content-Type, API-Key, API-Secret, Access-Control-Allow-Headers", "Access-Control-Expose-Headers": "sessionId", "Access-Control-Allow-Credentials": "true" },
     "continue": true
    },
    { "src": "/user/login", "methods": ["POST"], "dest": "index.js" }
  ]
}

Even added statusCode 200 to all my responses, but without any success. Removing the Npm-cors-package won't change anything, but removing the Now.json totally destroys stuff, and I get this error, from MDN even though I have it specified in my app.use(cors()).

Not really sure what to do, have been struggeling with this forever. No problem with cURL or other hosts where I can use backend proxy.

3
  • 1
    Quotes are not balanced in 'allowedHeaders': ['Content-Type', 'API-Key', 'API-Secret', 'Access-Control-Allow-Headers'', 'accept', 'client-security-token']. Is that the problem, or is it just a typo in your question? In case of the latter, that makes me wonder how well your question represents your actual configuration. Sep 3, 2019 at 10:27
  • 1
    You cannot set origin to a wildcard and include credentials! Please see developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/…
    – GuyT
    Sep 3, 2019 at 11:15
  • Have you tested using Postman?
    – gilbert-v
    Sep 3, 2019 at 13:02

7 Answers 7

8

You may need to enable pre-flight requests for your route

app.use(cors())

app.options('/post/login', cors()) // enable pre-flight requests
app.post('/post/login', (req, res, next) => {
    // your code here
});

or for all routes

app.options('*', cors())
2
  • From chrome: "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." Aug 26, 2019 at 21:19
  • I get this in firefoz: developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/… even though I specify the "origin" to "*" in cors() Aug 26, 2019 at 21:43
3

You can set the HTTP status of the pre-flight response.

app.options('*', function (req,res) { res.sendStatus(200); });
1

I got this cryptic error when the preflight (OPTIONS) request returned a 404. I eventually found I was using an incorrect path, and my router (Golang httprouter) 404s OPTIONS for non-existent routes.

0

you can use nginx's reverse proxy to proxy your 80 port's requests to 3000 port and it will work fine

0

Please try by adding one line and remove your old cors config from express and now.json

app.use(cors());

That’s it. CORS is now enabled. If you make a request to your app, you will notice a new header being returned: Access-Control-Allow-Origin: *

0

I use Nginx for cors configuration. But for local development in docker it's better to use express middleware:

const corsMiddleware = (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
        .header('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range')
        .header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE,PATCH');

    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
}
app.use(corsMiddleware);
-1

https://cors-anywhere.herokuapp.com/yoururl

Example:

axios.get('https://cors-anywhere.herokuapp.com/spo.handball4all.de/Spielbetrieb/index.php?orgGrpID=56&score=45991')
    .then(response => {
      const $ = cheerio.load(response.data);
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.