我想我的角度應用程序連接到我的節點服務器,我不想讓我的路線在服務器上的文件,所以我有一個節點服務器文件看起來像這樣CORS問題節點JS
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
var router = express.Router();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var cors = require('cors');
app.use(cors())
var db ='mongodb://localhost:27017/demo'
mongoose.connect(db,function(err){
if(err){
console.log("err");
}
else{
console.log("coonected to db");
}
})
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.set('views', path.join(__dirname,'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
app.use(express.static(path.join(__dirname,'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',function(req,res){
console.log("you have reached server");
res.json('wtf');
})
module.exports = app;
require('./route.js');
app.listen(port);
在route.js我有這樣我的路線
var login = require ('./api/login');
var app = require('./server')
app.get('/login',login.authenticate);
它工作正常,如果我使用節點服務器上,但如果我用它的角服務器上就說明這個錯誤:
從重定向「本地主機:3000 /登錄'到'localhost:3000/login /'已被CORS策略阻止:在請求的資源上沒有'Access-Control-Allow-Origin'標頭。因此不允許訪問Origin'localhost:4200'。
It only happens to the routes that I define in `route.js`. If I define the same route in `server.js` they work fine.
PS: I have also used
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
}); and some variation of this code but nothing works if I want to route to login url which is in my route file
爲什麼你在routes.js裏面配置你的應用程序? – echonax
我是新來的節點,我想保持路線在一個單獨的模塊 –
這很好,但這是你的快速設置的配置,可以保持你的server.js中的表達相關的配置是好的。但是,如果您可以在routes.js中添加用法,也許我們可以找到解決方案。 – echonax