0

Hi guys I'm trying to send an ajax request to my meteor app and handle it some way. Here is my code.

import { WebApp } from 'meteor/webapp'
import ConnectRoute from 'connect-route'
import { Popups } from '../../imports/collections/popups/Popups'

const Fiber = Npm.require('fibers')

function onRoute (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  let rawPostBody = ''
  let postData = {}
  req.on('data', function (chunk) {
    console.log('on data')
    rawPostBody += chunk.toString()
  })
  req.on('end', function () {
    console.log('on end')
    postData = getPostData(rawPostBody)
    console.log('postData', postData)
    console.log('postData.event', postData.event)
    console.log('postData._id', postData._id)
    Fiber(() => {
      Meteor.call('updateAnalytics', postData, (error, result) => {
        if (error) {
          console.log('updateAnalytics error', error)
        }
        if (result) {

        }
      })
      console.log('res', res)
      res.writeHead(200)
      res.end()
    }).run()
  })
}

function getPostData (rawPostBody) {
  let postData = {}
  let pairs = rawPostBody.split('&')
  for (let i = 0; i < pairs.length; i++) {
    let kv = pairs[i].split('=')
    postData[kv[0]] = decodeURIComponent((kv[1] + '').replace(/\+/g, '%20'))
  }
  return postData
}

const middleware = ConnectRoute(function (router) {
  // 2uik9 is for webhooks requests
  router.post('/handlePopups', onRoute)
})

WebApp.connectHandlers.use(middleware)

Now when I do an ajax request from chrome console I get this error

XMLHttpRequest cannot load https://b2c.meteorapp.com/handlePopups. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.

Also nothing is logged in my server console. But didn't I set the headers? Am I doing it wrong? Also note when I use a test http request service like Hurl.it it gets a response where it shows there are the headers

HEADERS

Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Origin: *
Content-Length: 0
Content-Type: text/plain; charset=utf-8
Date: Tue, 14 Mar 2017 10:39:59 GMT
Set-Cookie: galaxy-sticky=ESEFdEqGgiFCeS9P9-ras9; Path=/; HttpOnly

And my server console logs everything as it should.

So if my headers are all set what's the problem here?

UPDATE

Thanks to mutdmour and Alianp the error is gone, however there is yet another error XMLHttpRequest cannot load https://b2c-hayk94.c9users.io/handlePopups. Response for preflight is invalid (redirect) Do you know what's this error is about?

UPDATE

Apparently it was a c9 issue. After deploying to galaxy both answers work like a charm, however I accept Alianp's one, because that way I just set the headers for a specific route only.

Hayk Safaryan
  • 1,639
  • 1
  • 24
  • 44
  • Are you testing the pre-flight OPTIONS request with hurl.it? Or just the subsequent GET or POST request? – Quentin Mar 14 '17 at 10:51
  • @Quentin I think Hurl.it isn't sending an ajax request, so there is no preflight. But why the preflight request doesn't get the headers I set in its response? – Hayk Safaryan Mar 14 '17 at 10:57
  • I have been having similar issues recently, does this question help? http://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check-angularjs I found user a browser extension allowed my code to work, a more permanent solution for me would be to configure the server. – Ginger Squirrel Mar 14 '17 at 11:00

2 Answers2

1

Try this

//server/main.js
WebApp.rawConnectHandlers.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  return next();
});
mutdmour
  • 535
  • 5
  • 13
1

You need to enable OPTIONS method for CORS checking.

router.options('/handlePopups', function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin,X-Requested-With, Content-Type, Accept');
   res.writeHead(200);
   res.end();
});

Add this code inside ConnectRoute function and check it.

Irfan Ali
  • 1,998
  • 1
  • 20
  • 22
  • Thank you very much. This results in `XMLHttpRequest cannot load https://b2c-hayk94.c9users.io/handlePopups. Response for preflight is invalid (redirect)` Do you know what's this error is about? – Hayk Safaryan Mar 14 '17 at 11:23
  • Well apparently this was some issue with c9. After uploading to the galaxy this works like a charm, thanks! – Hayk Safaryan Mar 15 '17 at 05:44