对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标题存在于角度js中

时间:2016-01-20 06:52:46

标签: javascript mysql angularjs node.js

我使用nga admin使用节点js我是角度js和节点js的新手。我已经使用mysql节点js在localhost上创建了rest api,我使用postman检查它并且它工作正常。但是当我解析这个api url时,它会给我以下错误。看我想创建管理面板供用户编辑删除和更新只需要实现基本的东西。但是它的'向我显示404错误HEADERS ERROR。

XMLHttpRequest无法加载http://localhost:3000/api/user?_page=1&_perPage=30&_sortDir=DESC&_sortField=id。对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' http://localhost'因此不允许访问。 Server.js文件包含以下代码。

server.js文件

var express  = require('express'),
path     = require('path'),
bodyParser = require('body-parser'),
app = express(),
expressValidator = require('express-validator');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.json());
var connection  = require('express-myconnection'),
mysql = require('mysql');


app.use(

connection(mysql,{
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'gkv',
    debug    : true //set true if you wanna see debug logger
},'request')

 );

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

var router = express.Router();

router.use(function(req, res, next) {
console.log(req.method, req.url);
 console.log(res.headers);
next();
});

var curut = router.route('/user');

curut.get(function(req,res,next){
res.header("Access-Control-Allow-Headers","Content-Type");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST,OPTIONS");

req.getConnection(function(err,conn){

    if (err) return next("Cannot Connect");

    var query = conn.query('SELECT * FROM users',function(err,rows){

        if(err){
            console.log(err);
            return next("Mysql error, check your query");
        }
   res.json({message: 'All users!',data: rows });
        //res.render('user',{title:"RESTful Crud Example",data:rows});

     });

     });

     });


 app.use('/api', router);
     var server = app.listen(3000,function(){

      console.log("Listening to port %s",server.address().port);

 });

admin.js文件

var myApp = angular.module('myApp', ['ng-admin']);
myApp.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;

//Remove the header containing XMLHttpRequest used to identify ajax call 
//that would prevent CORS from working

delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common["Access-Control-Allow-Origin"] = "*";
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["content-type"] = "application/json";
});

myApp.config(['NgAdminConfigurationProvider', function (nga) {


// create an admin application
var admin = nga.application('My First Admin')
  .baseApiUrl('http://localhost:3000/api/'); // main API endpoint
// create a user entity
// the API endpoint for this entity will be      'http://jsonplaceholder.typicode.com/users/:id
var user = nga.entity('user');
// set the fields of the user entity list view
user.listView().fields([
    nga.field('Nachname').isDetailLink(true),
    nga.field('Anrede'),
    nga.field('Emailadresse'),
    nga.field('Telefonummer'),
     nga.field('Date&Time'),
     nga.field('URL'),
     nga.field('UserIP'),
]);
user.creationView().fields([
nga.field('Nachname'),
nga.field('Anrede'),
nga.field('Emailadresse'),
nga.field('Telefonummer'),
nga.field('Date'),
nga.field('URL'),
nga.field('UserIP')

]);
//user.editionView().fields(user.creationView().fields());
admin.addEntity(user);
/*var post=nga.entity('posts');
post.listView().fields([
nga.field('id'),
nga.field('title'),
nga.field('userId','reference').targetEntity(user).targetField(nga.field('username')).label('User'),
nga.field('comments','referenced_list').targetEntity(nga.entity('comments')).targetReferenceField('postId').targetFields([nga.field('email'),nga.field('name')]).sortField('id').sortDir('DESC')
]);*/
// add the user entity to the admin application

 //admin.addEntity(post);
// attach the admin application to the DOM and execute it
nga.configure(admin);
}]);

2 个答案:

答案 0 :(得分:1)

我通过在“app.js”文件中添加以下内容解决了我的问题,就像魅力一样。

var app = express()
, cors = require('cors')
, app = express();
app.use(cors());

答案 1 :(得分:-2)

以上查询已经解决,因为我使用了核心软件包npm并使用节点js cmd安装它并在server.js文件中添加了以下代码

cors = require('cors');
// use it before all route definitions
app.use(cors({origin: 'http://localhost'}));