2017-10-20 29 views
0

ローカルMongodbデータベースからデータをフェッチしているnodejsにローカルREST APIサーバを作成しました。また、サーバーからローカルにこのデータを要求する基本的なWebページも作成しました。私は、Webページからデータを取得しようとする今、それは私に次のエラーを与える:ローカルNodejsサーバでクロス・オリジン・リクエストを許可できません

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4000/todos. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). 

私はstackoverflowの上について検索し、THISTHIS解決策を見つけました。メインのapp.jsファイルに提案されたヘッダーを追加しました。しかしそれでも同じエラーが出ます。

以下は私のサーバーの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 routes = require('./routes/index'); 
var users = require('./routes/users'); 
var todos = require('./routes/todos'); 

// load mongoose package 
var mongoose = require('mongoose'); 

// Use native Node promises 
mongoose.Promise = global.Promise; 

// connect to MongoDB 
mongoose.connect('mongodb://localhost/todo-api') 
.then(() => console.log('connection succesful')) 
.catch((err) => console.error(err)); 

var app = express(); 

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

// 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'))); 

app.use('/', routes); 
app.use('/users', users); 
app.use('/todos', todos); 

// Add headers 
app.use(function (req, res, next) { 

    // Website you wish to allow to connect 
    res.setHeader('Access-Control-Allow-Origin', '*'); 

    // Request methods you wish to allow 
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); 

// Request headers you wish to allow 
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); 

// Set to true if you need the website to include cookies in the requests sent 
// to the API (e.g. in case you use sessions) 
res.setHeader('Access-Control-Allow-Credentials', true); 

// Pass to next layer of middleware 
next(); 
}); 
// 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 handlers 

// development error handler 
// will print stacktrace 
if (app.get('env') === 'development') { 
    app.use(function(err, req, res, next) { 
    res.status(err.status || 500); 
    res.render('error', { 
     message: err.message, 
     error: err 
    }); 
    }); 
} 

// production error handler 
// no stacktraces leaked to user 
app.use(function(err, req, res, next) { 
    res.status(err.status || 500); 
    res.render('error', { 
    message: err.message, 
    error: {} 
    }); 
}); 

module.exports = app; 

次に、私のAPIからデータを取得したいWebページのコード(Angularjs)を示します。

dbConnection.html

<html ng-app="demo"> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"> </script> 
<head> 
    <title> dbConnection Demo</title> 
</head> 

<body ng-controller="db"> 
    <div ng-repeat="product in db.products"> 
     {{product._id}} </br> 
    </div> 
</body> 

<script> 
    var app = angular.module('demo', []); 
    app.controller('db', ['$http', function($http){ 
     var store = this; 
     store.products = []; 

     $http({ 
      method: 'GET', 
      url: 'http://localhost:4000/todos' 
      }).then(function (success){ 
       store.products = success; 
      },function (error){ 

      }); 
    }]); 
</script> 
</html> 

の回答で提案されているように、私は、ヘッダーを追加した後でも、私は同じエラーを取得しています。私はここで何が欠けていますか?私はこの分野では全く初心者です。ありがとう!

+0

[CORSミドルウェア](https://github.com/expressjs/cors) –

+0

をお試しください。ただし、どこで使用しますか? – Kaushal28

+0

リンクの[documentation](https://github.com/expressjs/cors#usage)に詳しい説明があります。 –

答えて

0

私は最終的に、私のルートにこれらのヘッダを追加することによって、解決策を次のように考え出しました:

routes/todos.js

... 
... 
router.get('/', function(req, res) { 
res.setHeader('Access-Control-Allow-Origin', '*'); 
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed 
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,contenttype'); // If needed 
res.setHeader('Access-Control-Allow-Credentials', true); // If needed 

res.send('cors problem fixed:)'); 
}); 
0

あなたは追加する必要があります:

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 

なぜ?まあ、私も同じ問題があったと思いますが、これで解決しました。

+0

前のメソッドを削除した後にこの行を追加しましたか? – Kaushal28

+0

同じエラーが発生しています – Kaushal28

0

var app = express(); の後にヘッダーコードを移動してください。つまり、ルータを定義する前に配置する必要があります。

var app = express(); 
app.use(function (req, res, next) { 

// Website you wish to allow to connect 
res.setHeader('Access-Control-Allow-Origin', '*'); 

// Request methods you wish to allow 
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); 

// Request headers you wish to allow 
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); 

// Set to true if you need the website to include cookies in the requests sent 
// to the API (e.g. in case you use sessions) 
res.setHeader('Access-Control-Allow-Credentials', true); 

// Pass to next layer of middleware 
next(); 
}); 

// Router 
+0

コードを参照してください。私の 'app.js'。 – Kaushal28

+0

私はあなたがルータの前に置く必要があることを意味する –

1

あなたのリクエストには飛行前の応答が必要ですか?そうであれば、メソッド 'OPTIONS'でエンドポイントにヒットしようとします。設定していなければ、corsの問題が表示されます。

ですから、プリフライト応答が失敗していることを発見した場合、あなたはNPMのCORSパッケージカスタムオプションルート、または潜在的な使用を追加するか - あなたのapp.jsでhttps://www.npmjs.com/package/cors

npm install cors --save 

var cors = require('cors') 


app.options('*', cors()) // include before other routes 
app.use(cors()) 
関連する問題