不一致的错误'No'Access-Control-Allow-Origin'标头出现在请求的资源上'

时间:2017-09-16 17:26:52

标签: node.js http https http-headers cors

我知道像这样的问题已被多次回答,但没有一个答案能够帮助我。请在下载之前先解决我的问题。

Referred Stackoverflow Solutions:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API \

How to allow CORS?

var http=require('http');
var istanbul = require('istanbul');
var fs = require('fs');
var path=require('path');
var cors = require('cors');
var Express = require('express');
var options = {
  embedSource : true
};
var instrumenter = new istanbul.Instrumenter(options);
var headers = {};
headers['Access-Control-Allow-Origin'] = '*';
var server = Express();



//Handing CORS Issue
server.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

//Handling Ping for tying VIP with Host
server.get('/ping',function(request,response,next){
  response.status(200).send('You reached server.Go ahead!')
});

server.use('/', function(request, response, next) {
    var cdn = request.url; // Fetching whatever comes after proxy host name
    var subStringCSS=".css";
    var subStringJS=".js";
    var reg= /[http].*/;
    var result = cdn.match(reg); // Fetching CDN URL
    var out = decodeURIComponent(result);
    var urlToHit = out.toString();

// This if condition makes sure that CSS files are directly called & returned
// back to OTP without Instrumentation
    if (urlToHit.includes(subStringCSS))
    {
        http.get(urlToHit, function(res)
        {
          var str='';
          headers['content-type'] = 'text/css';
          response.writeHead(200, headers);
          res.on('data',function(body)
          {
            str+=body;

          })
          .on('err', function(e)
          {
            console.log('Error when calling CDN ' + e.message)
          })
          .on('end',function()
          {
            response.write(str);
            response.end();
          })
          .setEncoding('utf-8');
        });
    }

// This if condition returns Instrumented JS assets
    if (urlToHit.includes(subStringJS))
    {
      try
      {
        http.get(urlToHit, function(res)
        {
          var str='';
          headers['content-type'] = 'text/javascript';
          response.writeHead(200, headers);
          res.on('data',function(body)
          {
            str+=body;
          })
          .on('err', function(e)
          {
            console.log('Error when calling CDN ' + e.message)
          })
          .on('end',function()
          {

            var nameOfFile = urlToHit.split('?');
            var assetFileName = nameOfFile[1].split('/');
            var fileName = assetFileName[1].concat(".js");
            var pathToSrcFile = __dirname.concat("/src-files/");// Place to save Downloaded JS file
            var filePath = path.join(pathToSrcFile, fileName); // Name of the file being downloaded
            var writeStream = fs.createWriteStream(filePath,{mode: 0o777});
            writeStream.write(str); //Writing downloaded assets to a file
            var instrumented = instrumenter.instrumentSync(str,fileName);// Instrumenting Assets
            response.write(instrumented);// Sending the instrumented assets back
            response.end();
          })
          .setEncoding('utf-8');
        });
      }
      catch(e)
      {
        console.log(e);
      }
    }
});
server.listen(8000,function(){
console.log('Listening on 8000');
});

使用上面的代码片段,我曾经遇到过CORS问题,但我通过添加以下代码解决了这个问题:

server.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

但是几个月后突然间,我又开始重新回到同一个CORS问题。错误如下所示:

  

来自“客户端”的“服务器”访问脚本已被阻止   CORS策略:没有'Access-Control-Allow-Origin'标题出现在   请求的资源。因此,不允许原始“客户”访问。   响应具有HTTP状态代码503

有人可以指出我为什么会遇到上述错误?

我尝试过使用npm'cors',但没有运气。我也试过提供'*'的确切Origin insese,但问题仍然存在。

0 个答案:

没有答案