Nodejs允许跨源问题

时间:2018-03-10 19:38:16

标签: javascript node.js angular cross-domain

我有一个连接到node.js中的服务器应用程序的客户端应用程序,我已经在设置路由之前设置了允许来源,但它仍然给我一个跨源问题。

所以我有角度应用程序调用服务像这样

app.service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
// import * as config from '../../../../config.json';

@Injectable()
export class PDFService {
  constructor (private http: Http) {}
  generatePDF() {
    return this.http.get("localhost:8000/pdfURL")
    .map((res:Response) => res.json());
  }
}

app.component

import { Component } from '@angular/core';
import { PDFService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  constructor(private pdfService: PDFService) {
  }

  generatePDF() {
    this.pdfService.generatePDF().subscribe(
      (response) => {
        console.log("pdf generated");
      },
      (error) => {
        console.log("something went wrong on generating pdf");
      }
    );
  }
}

点击一个简单的按钮调用上面的函数。

在服务器端,我的app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var router = express.Router();
var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

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

app.use('/',require('./routes/index'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

允许来源调用路由初始化后的app.use:

var express = require('express');
var router = express.Router();

router.use('/',require('./pdfGenerator'))

router.use(function(req,res,next){
    return res.status(404).json({Error:"Invalid Url"});
})

module.exports = router;

最后我打电话给pdfGenerator路由器:

var express = require('express');
var router = express.Router();
var pdfGenerator = require('../controllers/pdfGenerator');

router.get('/pdfURL', pdfGenerator.pdfToUrl);

module.exports = router;

调用控制器:

var express = require('express');
var router = express.Router();
var fs = require('fs');
var pdf = require('html-pdf');
//var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };


module.exports = {
    pdfToUrl: function(req,res,next) {
        console.log("adas");
        pdf.create('<div style="background-color:blue">a simple text</div>', options).toFile('./businesscard.pdf', function(err, res) {
            console.log("asd"); // { filename: '/app/businesscard.pdf' }    
            if (err) return console.log(err);
            console.log("asd"); // { filename: '/app/businesscard.pdf' } 
          });
    }
};

我和邮递员一起尝试过,它的效果很好吗?

1 个答案:

答案 0 :(得分:0)

尝试安装Cors:https://www.npmjs.com/package/cors 并像这样使用它:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

您当然也可以使用插件。例如,在chrome:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

希望这会有所帮助;)