So in my app I have CORS headers set like this
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
And it works like a charm.
I can do an ajax request right here from stackoverflow using the console and get a response.
And everything seems to be working fine.
However there is just one website, from which I do an ajax request to the same file and get an error as if the headers are not set.
Here is the error
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is my serverside 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.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()
})
router.post('/handlePopups', onRoute)
})
WebApp.connectHandlers.use(middleware)
And here is my ajax code
const data = {event: 'impression', _id:'randomid'}
$.ajax({
method: 'POST',
contentType: 'application/json',
url: 'https://example.com/handlePopups',
data
}).success((res) => {
console.log('ajax res', res)
}).error((err) => {
console.log('ajax err', err)
})
Why? How is that even possible?