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?