在CORS上拒绝本地主机连接

时间:2017-01-10 20:21:32

标签: angularjs express cors

我无法与其他有类似问题的人解决这个问题。我正在尝试截取我的应用程序的屏幕截图(在端口3005上运行)并将其存放在单独的本地域(在端口1337上运行)。当我尝试在浏览器上访问localhost:1337时,我也得到“无法访问网站”。该函数运行正常,但是当它进入POST时我收到错误。

我的错误说明:

  

选项http://localhost:1337/screenshot net :: ERR_CONNECTION_REFUSED

我正在使用Angular,这是我的server.js:

var express = require( "express" );
var http    = require( "http" );
var bodyParser = require('body-parser');
var app     = express();
var webshot = require('webshot');
var cors = require('express-cors');
var AWS = require('aws-sdk');
var Readable = require('stream').Readable;
var fs = require('fs');
AWS.config.loadFromPath('./aws-config.json');

app.use(cors({
    allowedOrigins: [
        'localhost:3005'
    ]
    headers: [
        'Access-Control-Allow-Credentials','x-xsrf-token', 'Content-Type', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Methods', 'Access-Control-Allow-Headers'
    ]
}));

allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  if ('OPTIONS' === req.method) {
    res.send(200);
  } else {
    next();
  }
};

app.use(allowCrossDomain);


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.post( "/screenshot", function ( req, res ) {


    var options = {
        siteType: 'html',
        customCSS: css,
        defaultWhiteBackground: true,
        windowSize: {
            width: 1100,
            height: 600
        },
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36'
    };

    webshot( req.body.html, null, options, function ( err, stream ) {
        var generateRandomNumber = function () { return Math.floor((Math.random() * 10000000) + 1); };

        var s3 = new AWS.S3({ params: { Bucket: 'buddi-screenshots', Key: 'buddi-screenshot_' + generateRandomNumber() + '.png'  } });

        var readableStream = new Readable().wrap(stream);

        s3.upload({ Body: readableStream }, function(err, data) {
            if(err) return console.log(err);

            res.send( { data: data.Location } );
            res.end();
        });
    });

});

http.createServer( app ).listen( 1337 );

我的控制器功能:

$scope.takeScreenShot = function() {  
        // Grabs HTML tags and everything in between
        var html = document.documentElement.outerHTML;

        // Add Endpoint URL, Pass Data Object
        $http.post("http://localhost:1337/screenshot", { html: html } )
          .then(function (response) {
            // Define your scoped var and set it to returned data
            self.ssUrl = response.data.data;
          });
        console.log('screenshot taken');
        $scope.screenshot = true;
    }

0 个答案:

没有答案