可能的控制器或至少执行两次的功能

Posted

技术标签:

【中文标题】可能的控制器或至少执行两次的功能【英文标题】:Possible Controller or at least the functions executing twice 【发布时间】:2017-10-03 11:38:19 【问题描述】:

所以我收到此错误:“GET http://localhost:8000/blogs/undefined net::ERR_EMPTY_RESPONSE angular.js:12587”。

当我访问我的主博客页面和访问博客类别页面时会发生这种情况。查看我得到的网络选项卡: 1. blog-home.html 200 xhr angular.js 12587 4.6kb 21ms 2. 所有 200 xhr angular.js 12587 3.0kb 57ms 3.未定义待处理的xhr angular.js 12587 3.0kb 57ms 0kb

当我进入博客类别页面时也是如此。最终他们失败并踢出上面的错误。

所以在这被否决之前......我已经在堆栈上阅读并尝试过: 没有运气。也许我错过了什么或输入了错误的东西。我完全傻眼了,我觉得这显然超出了我的技能水平。所以这里有一堆代码...... 服务器.js

var express = require('express');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var Mailgun = require('mailgun-js');
var path = require('path');
require('colors');

var app = express();


app.use(favicon(path.join(__dirname, 'client/assets/images', '*****')))

app.use(bodyParser.urlencoded(extended:true));
app.use(bodyParser.json(extended:true))

app.use(express.static(path.join(__dirname, 'client')));
app.use(express.static("./bower_components"));

//app.all('/*', function(req, res, next) 			    
//    res.sendFile('index.html',  root: 'client');
//);

require('./server/config/mongoose.js');

var routes = require('./server/config/routes.js');
routes(app);

var api_key = '*********';
var domain = '*********';
var mailgun = require('mailgun-js')(apiKey: api_key, domain: domain);
 
var data = 
  from: '********',
  to: '********',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomness!'
;
 
mailgun.messages().send(data, function (error, body) 
  console.log(body);
);

app.listen(8000, function () 
  console.log("I'm listening...".blue);
)

索引.html

<!DOCTYPE html>
<html lang="en" ng-app="Bridgeman">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="revisit-after" content="10 days">
    <meta name="googlebot" content="noodp">
    <meta name="msnbot" content="noodp">
    <meta name="slurp" content="noodp, noydir">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ; connect-src 'self'; img-src * data:; style-src 'self' 'unsafe-inline'; font-src * data:; frame-src https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d44591.890384371676!2d-118.36723983279781!3d33.83006153459027!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2sus!4v1492366398808 ">
    
    
    <meta content="/assets/images/******_BigBearSnowTrail.jpg" itemprop="image">
    <link href="/assests/images/*******.ico" rel="shortcut icon">

    <base href="/" />

    <title></title>
  
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">   
    <link href="assets/css/modern-business.css" rel="stylesheet"> 
    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <script type="text/javascript" src="angular/angular.js"></script>
    <script type="text/javascript" src="angular-route/angular-route.js"></script>
    <script src="app.js"></script>

    <script src="/factories/ContactFactory.js"></script>
    <script src="/factories/loginFactory.js"></script>
    <script src="/factories/blogFactory.js"></script>

    <script src="/controllers/contactController.js"></script>
    <script src="/controllers/servicesController.js"></script>
    <script src="/controllers/blogController.js"></script>
    <script src="/controllers/blogViewController.js"></script>
    <script src="/controllers/blogAWSController.js"></script>
    <script src="/controllers/loginController.js"></script>
  
    <base target="_blank">
</head>

<body>

    <div ng-include='"templates/header.html"'></div>
    <div ng-view=""></div>
    <div ng-include='"templates/footer.html"'></div>

    
   
    <script src="assets/js/jquery.js"></script>    
    <script src="assets/js/bootstrap.min.js"></script>    
</body>
</html>

app.js(如您所见,我试图将 AWS 类别分离到它自己的控制器中,并且在加载该页面时都会触发)

var Bridgeman = angular.module('Bridgeman', ['ngRoute']);

	Bridgeman.config(['$routeProvider', '$httpProvider', '$locationProvider', '$qProvider', function($routeProvider, $httpProvider, $locationProvider, $qProvider)
			$qProvider.errorOnUnhandledRejections(false);
			$httpProvider.interceptors.push(function($q, $location)									
				return
					'responseError': function(rejection)
						if(rejection.status == 401)
							$location.url('/');
						
						return $q.reject(rejection);
						
					
				);
			$routeProvider
				.when('/', 
					templateUrl:'partials/home.html',					
				).when('/about', 
					templateUrl:'partials/about.html',					
				).when('/services', 
					templateUrl: 'partials/services.html',
					controller: 'servicesController'
				).when('/blog', 
					templateUrl: 'partials/blog-home.html',
					controller: 'blogViewController'
				).when('/blogAWS', 
					templateUrl: 'partials/blog-aws.html',
					controller: 'blogAWSController'
				).when('/blogSEO', 
					templateUrl: 'partials/blog-SEO.html',
					controller: 'blogViewController'
				).when('/blogSecurity', 
					templateUrl: 'partials/blog-Security.html',
					controller: 'blogViewController'
				).when('/blogBusiness', 
					templateUrl: 'partials/blog-Business.html',
					controller: 'blogViewController'
				).when('/blogSportsTech', 
					templateUrl: 'partials/blog-SportsTech.html',
					controller: 'blogViewController'
				).when('/blog-post/:id', 
					templateUrl: 'partials/blog-post.html',
					controller: 'blogViewController'					
				).when('/contact', 
					templateUrl: 'partials/contact.html',
					controller: 'contactController'
				).when('/login', 
					templateUrl:'partials/login.html',
					controller: 'loginController'
				).when('/admin', 
					templateUrl:'partials/admin.html',
					controller: 'blogController'
				).otherwise(
					redirectTo:'/'
				);
			$locationProvider.html5Mode(true);
		])

	Bridgeman.run(function($rootScope, $location, $anchorScroll, $routeParams) 
  		$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) 
    		$location.hash($routeParams.scrollTo);
    		$anchorScroll();  
  );
)

blog-home.html(这是在我的 blogViewController 中触发这两个功能的主博客页面)

<!-- Page Content -->
    <div class="container">

        <!-- Page Heading/Breadcrumbs -->
        <div class="row">
            <div class="col-lg-12">
                <h1 class="page-header">Blog Home 
                    <small>My insights just for you</small>
                </h1>
                <ol class="breadcrumb">
                    <li><a href="/blog">Home</a>
                    </li>
                    <li class="active">Blog Home</li>
                </ol>
            </div>
        </div>
        <!-- /.row -->

        <div class="row">

            <!-- Blog Entries Column -->
            <div class="col-md-8">
              <div class="blogs" ng-repeat="b in blogs | orderBy:'-createdAt' | filter:searchblogs">

                <!-- Blog Post -->
                <h2>
                    <p>b.title</p>
                </h2>
                <p class="lead">
                    by b._user.name in the b.category category
                </p>
                <p><i class="fa fa-clock-o"></i> Posted on b.createdAt | date: "MMM. dd, yyyy"</p>
                <hr>
                <p>b.snippet</p>
                <hr>
                <p>b.content</p>                
                <a class="btn btn-primary" ng-href="/blog-post/b._id">Read More <i class="fa fa-angle-right"></i></a>

                <hr>
              </div>
              <hr>
              </div>

            <!-- Blog Sidebar Widgets Column -->
            <div class="col-md-4">

                <!-- Blog Search Well -->
                <div class="well">
                    <h4>Search my blogs</h4>
                    <div class="input-group">
                        <input type="text" class="form-control" ng-model="searchblogs">
                        <span class="input-group-btn">
                            <button class="btn btn-default" type="button"><i class="fa fa-search"></i></button>
                        </span>
                    </div>
                    <!-- /.input-group -->
                </div>

                <!-- Blog Categories Well -->
                <div class="well">
                    <h4>Blog Categories</h4>
                    <div class="row">
                        <div class="col-lg-6">
                            <ul class="list-unstyled">
                                <li><a href="/blogAWS">AWS</a>
                                </li>
                                <li><a href="/blogSEO">SEO</a>
                                </li>
                                <li><a href="/blogSecurity">Security</a>
                                </li>
                                <li><a href="/blogBusiness">Business Tips</a>
                                </li>
                            </ul>
                        </div>
                        <!-- /.col-lg-6 -->
                        <div class="col-lg-6">
                            <ul class="list-unstyled">
                                <li><a href="/blogSportsTech">Tech in Sports</a>
                                </li>
                                <li><a href="#">Coming Soon</a>
                                </li>
                                <li><a href="#">Coming Soon</a>
                                </li>
                                <li><a href="#">Coming Soon</a>
                                </li>
                            </ul>
                        </div>
                        <!-- /.col-lg-6 -->
                    </div>
                    <!-- /.row -->
                </div>

                <!-- Side Widget Well -->
                <div class="well">
                    <h4>My Blog</h4>
                    <p>Here is a collection of my genius (ha!) and tech insights. I'm sure sooner than later I will discuss Formula 1 tech but be assured there will be plenty of SEO and various web development tips/tools/tricks. And lets not forget some general business savviness I've learned over the years.</p>
                </div>
            </div>
        </div>
        <!-- /.row -->

blogViewController(函数在哪里。同样,我注释掉了 getOneBlog 并且没有发生错误。那么在单击按钮之前触发此火灾的原因是什么?)

Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams)
  console.log("in the blog VIEW controller");

  $scope.blogs = [];
  $scope.one = [];

  blogFactory.getAllBlogs(function(output)
    $scope.blogs = output;
    console.log(output);
  )

  blogFactory.getOneBlog($routeParams.id, function(output)
    $scope.one = output;
    console.log(output);
  )
);

blogFactory(我知道这里没有问题)

Bridgeman.factory('blogFactory', function($http)
  var factory = ;

  factory.submitNewBlog = function(input, callback)
    $http.post('/blogs/new', input).then(function(output)
      console.log("we just added a new blog");
      callback(output.data);
    );
  
  //factory.submitNewComment = function(input, callback)
  //  $http.post('/comments/new', input).then(function(output)
  //    console.log("we just added a new comment");
  //    callback(output.data);
  //  );
  //

  factory.getAllBlogs = function(callback)
    $http.get('/blogs/all').then(function(output)
      console.log("we just got all blogs");
      callback(output.data);
    );
  

  factory.getOneBlog = function(blogID, callback)          //factory.getOneBlog = function(blogID, callback)
    $http.get('/blogs/' + blogID).then(function (output)          //$http.get('blogs/' + blogID).then(function (output)
      console.log(output.data);                             //callback(output.data);
      console.log("we just got one blog");
      callback(output.data);
    );
  

  return factory;
);

路线(这里有几种不同的风格,只是结合不同的格式来解决这个问题)

var users = require('./../controllers/users.js');
var blogs = require('./../controllers/blogs.js');

module.exports = function(app)
	
	app.post('/reg', function(req, res)
	users.reg(req, res);
	);

	app.post('/login', function(req, res)
	users.login(req, res);
	);
	
	app.get('/blogs/all', function(req, res) 
        blogs.getAllBlogs(req, res);
    );

    app.get('/blogs/:id', blogs.getOneBlog); 			//app.get('/blogs/:id', blogs.getOneBlog)       
    

    app.post('/blogs/new', function(req, res) 
        blogs.addBlog(req, res);
    );

	app.post('/contact', function(req,res)

		var api_key = 'key-2451a2b90a87be616ab68b8f7c8f97ea';
		var domain = 'sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org';
		var mailgun = require('mailgun-js')(apiKey: api_key, domain: domain);
		 
		var data = 
		  from: 'Website inquiry <postmaster@sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org>',
		  to: '*************com',
		  subject: req.body.full_name+" has sent you a message",
		  html:
			  req.body.full_name+" ..."+			  
			  req.body.phone+" ..."+
			  req.body.email+" ..."+			  		  
		  	  req.body.message
		;
		 
		mailgun.messages().send(data, function (error, body) 
		  console.log(body);
		  console.log("working...");
		  if(!error)
		    res.send("Your message has been sent");
		  else
		  	res.send("Uh oh... something went wrong!");
		);
	);

blogs.js 服务器端控制器(这里没有问题...我知道)

var Blog = mongoose.model('Blog');

module.exports = (function() 
    return 
      getAllBlogs: function(req, res)
        Blog.find().populate([path : '_user']).exec(function(err, b)
          if(err)
            console.log("there was an error when getting all blogs".red);
           else 
            console.log(b);
            console.log("successfully got all blogs".green);
            res.json(b);
          
        );
      ,

      getOneBlog: function(req, res) 
        console.log('Rich band aid');
        if (req.params.id !== 'undefined') 
        console.log('there was an id', req.params.id); 
        Blog.findOne(_id: req.params.id).exec(function(err, b)         //(_id: req.params.id, function(err,b))
          if(err)
            console.log('error is', err);
            console.log("there was an error when getting the blog".red);
           else 
            console.log(b);
            console.log("successfully got the blog".green);
            res.json(b);
          
        );
       else 
        console.log('no id');
       
      ,

      addBlog: function(req, res) 
        console.log("===========================".yellow);
        console.log(req.body);
        console.log("===========================".yellow);

        var b = new Blog(category: req.body.category, title: req.body.title, snippet: req.body.snippet, content: req.body.content, _user: req.body._user)
        b.save(function(err)
          if(err)
            console.log("there was an error when saving a blog".red);
           else 
            console.log(b);
            console.log("successfully saved the above blog".green);

            res.redirect('/blogs/all');
          
        )
      
    
)();

还有 mongoose db(这里没有问题……我知道)

var mongoose = require('mongoose');

// Create the message schema
var BlogSchema = new mongoose.Schema(
	category: type: String, required: true, minlength: 3, enum:['Security', 'Business', 'SEO', 'AWS', 'Tech in Sports'],
	title: type: String, required: true, minlength: 3,
	snippet: type: String, required: true, minlength: 3,
    content: type: String, required: true, minlength: 3,
    _user: type: mongoose.Schema.Types.ObjectId, ref: 'User'    
, timestamps: true);

mongoose.model('Blog', BlogSchema);

非常感谢任何帮助。谢谢

PS...是的,当您尝试刷新页面时,我知道 frame-src 和 font-src 的 CPS 错误。超级烦。

【问题讨论】:

请检查你的角度路径, @RAj 感谢您的指导。我添加了 server.js,希望您能更详细地说明您的意思?非常感谢您抽出宝贵的时间和这个菜鸟。 @RAj 所以我一直在使用 angular 脚本标签,唯一有任何区别的事情是当我将 angular 和 angular-route 脚本标签移动到索引页面的底部时。当我这样做时,我可以转到我的博客主页,并且只是页面本身和 getAllBlogs 被触发。 getOneBlog 没有触发,也没有被卡住。不幸的是,页面上没有呈现任何博客。 请创建 jsfiddle,以便我调试问题。 @RAj - 感谢您的帮助,但请查看答案。花了一些时间,但我和一个朋友想出了一个解决方案。 【参考方案1】:

能够和朋友一起解决。通过将 2 个函数包装到“if”语句中解决了问题。它可能不是正确的解决方案,但效果很好。

Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams)
  console.log("in the blog VIEW controller");

  $scope.blogs = [];
  $scope.one = [];


  if ($routeParams.id) 
    blogFactory.getOneBlog($routeParams.id, function(output) 
    $scope.one = output;
    console.log(output);
    );
   else 
    blogFactory.getAllBlogs(function(output) 
    $scope.blogs = output;
    console.log(output);
    );
    
);

【讨论】:

以上是关于可能的控制器或至少执行两次的功能的主要内容,如果未能解决你的问题,请参考以下文章

求出被矩形覆盖过至少两次的区域的面积(扫描线 + 线段树)

使用axios发送请求,遇到会发两次的情况

C#控制台 延迟执行下一行语句

总是至少执行一次的 Python 循环? [复制]

用不同的语言编译同一个文件两次的惯用方法是啥?

PHP面试 PHP基础知识 八(会话控制)