0

I've inserted the following lines into my code:

var express = require('express');
var cors = require('cors');

var app = express();

app.options('*', cors());
app.use(cors());

However, when I make an AJAX POST request, I still get the error:

POST https://stormy-plateau-94715.herokuapp.com/login 
new-page-5:1 XMLHttpRequest cannot load https://stormy-plateau-94715.herokuapp.com/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://squareguru.squarespace.com' is therefore not allowed access. The response had HTTP status code 503.

This is my first time using the cors package, am I configuring something wrong? I would love any help you guys can give me, thanks!

Dan
  • 2,647
  • 2
  • 27
  • 37
  • Is stormy-plateau-94715 your app or someone else's – Jared Beach Jul 18 '16 at 14:31
  • It's my app. It's one of the free hobby dynos on Heroku. – Dan Jul 18 '16 at 14:33
  • Try adding this code to the top of your login endpoint: `res.setHeader("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With");` – Jared Beach Jul 18 '16 at 14:39
  • I added the following code: `app.all('*', function(req, res, next){ res.writeHead(200, {'Content-Type': 'text/html'}); res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });` I'm still getting the same error – Dan Jul 18 '16 at 14:41
  • Maybe try changing that to have a star instead of empty string here: `res.header("Access-Control-Allow-Origin", "*")` If it still doesn't work. Try moving that code directly into the post function to see if your `app.all` isn't working. Edit: I see that there is a star there now. – Jared Beach Jul 18 '16 at 14:45
  • You also might need `crossdomain:true` in your ajax post. Can you post your ajax code? See here: http://stackoverflow.com/questions/25923796/cors-error-with-jquery – Jared Beach Jul 18 '16 at 14:48
  • 1
    I guess you don't need `app.options('*', cors());` just `app.use(cors());` – Nodari Lipartiya Jul 18 '16 at 14:50
  • Also, your app appears to be crashed – Jared Beach Jul 18 '16 at 14:50
  • Haha that's embarrassing. Okay, moving all of those headers into my app.post('/login') function seemed to do the trick. Thanks so much for your help! If you post that as an answer, I can accept it as correct. – Dan Jul 18 '16 at 14:56
  • Nah, I'm not going to make an answer because it's not really what you asked. I'm curious why the CORS package didn't fix it for you or why app.all didn't work. Maybe someone will have a better solution. – Jared Beach Jul 18 '16 at 15:18

0 Answers0