所以在我的应用程序中,我有像这样设置的CORS标题
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
它就像一个魅力。 我可以使用控制台从stackoverflow在这里做一个ajax请求并获得响应。 一切似乎都运转正常。 但是,只有一个网站,我从中向同一个文件发出ajax请求并得到一个错误,好像没有设置标头一样。 这是错误
No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是我的服务器端代码
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)
这是我的ajax代码
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)
})
为什么呢?怎么可能呢?