js和Angular2进行CORS

js和Angular2进行CORS

本文介绍了使用Express.js和Angular2进行CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从远程Express.js服务器将PLY文件下载到Angular/Ionic应用程序.我现在将Ionic应用程序托管在Amazon AWS上.这是Ionic应用程序中的打字稿:

I'm trying to download a PLY file from my remote Express.js server to my Angular/Ionic app. I have my Ionic app hosted on Amazon AWS right now. Here's the Typescript from the Ionic app:

//this.currentPlyFile encompasses entire URL
document.getElementById('entity').setAttribute("ply-model", "src: url(" + this.currentPlyFile + ".ply);");

我的Express.js服务器中包含以下内容:

I have the following in my Express.js server:

app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Credentials', true);
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET,POST');
        res.header('Access-Control-Allow-Headers', 'appid, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
        if ('OPTIONS' == req.method) {
            res.send(200);
        } else {
            next();
        }
    });

但是当请求PLY文件时出现以下错误:

But I get the following error when requesting the PLY file:

XMLHttpRequest cannot load "my url here" No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'my url here' is therefore not allowed access.

这真令人沮丧,因为我正在使用Express.js文档提供的标头来允许CORS.

This is really frustrating because I am using headers provided by the Express.js documentation to allow CORS.

推荐答案

Preflight->选项-> https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS -> next()

Preflight -> Options -> https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS -> next()

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'appid, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});

app.get('/', function (req, res) {
  res.send('OK');
});

注意:将这些内容移至配置功能的顶部.

Note: Move that stuff to the top of your configure function.

或者简单使用表达cors :

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

app.use(cors());

app.get('/', function (req, res) {
    res.send('OK');
});

这篇关于使用Express.js和Angular2进行CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:01