小编Nan*_*ano的帖子

node.js无法在同一文件夹中找到模块

我试图使用一个简单的"颜色"模块来设置我的日志中的cli颜色,没什么特别的.

好吧,我有一个colors.js在路径中调用的模块./app/config/colors.js,内容:

var clc = require('cli-color');

var colors = {
  ok: clc.cyan,
  error: clc.red.bold,
  warn: clc.yellowBright,
  high: clc.white.bgGreen
};

module.exports = colors;
Run Code Online (Sandbox Code Playgroud)

简单.好吧,当我在server.js中需要它时(在项目的根目录,在/ app之上)它工作正常,但是,当我尝试在它中使用它时./app/config/db.js会抛出一个错误:

Error: Cannot find module './app/config/colors.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/nano/Dev/bears-api/app/config/db.js:3:14)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
14 Sep 10:21:00 - [nodemon] app crashed - waiting for file changes before starting...
Run Code Online (Sandbox Code Playgroud)

为什么它在server.js中有效?

node.js

13
推荐指数
1
解决办法
1万
查看次数

手写笔给我一个预期的"缩进",得到"突出",但我不知道为什么

这很奇怪我只是在变量设置中进行更改以使用哈希代替...你知道:

black = #000
Run Code Online (Sandbox Code Playgroud)

被替换为:

colors = {
    'black': #000
     // and so on...
}
Run Code Online (Sandbox Code Playgroud)

然后,我替换代码(ofcourse)中的所有变量调用,并且所有模块编译得很好,除了一个,这是跟踪:

ParseError: ../../dopamine/components/_ui.styl:26
   22|     notice(clr: -colors['light-blue'])
   23|     color -colors['white']
   24|     font-weight bold
   25|     text-shadow 1px 1px 1px rgba(#000, .2)
 > 26|   
   27|   if type == "success"
   28|     notice(clr: -colors['green'])
   29|     color -colors['white']

expected "indent", got "outdent"

    at Parser.error (/usr/local/lib/node_modules/stylus/lib/parser.js:230:11)
    at Parser.expect (/usr/local/lib/node_modules/stylus/lib/parser.js:258:12)
    at Parser.block (/usr/local/lib/node_modules/stylus/lib/parser.js:741:12)
    at Parser.selector (/usr/local/lib/node_modules/stylus/lib/parser.js:1277:24)
    at Parser.property (/usr/local/lib/node_modules/stylus/lib/parser.js:1228:47)
    at Parser.ident (/usr/local/lib/node_modules/stylus/lib/parser.js:1183:25)
    at Parser.stmt (/usr/local/lib/node_modules/stylus/lib/parser.js:685:26)
    at Parser.statement (/usr/local/lib/node_modules/stylus/lib/parser.js:593:21)
    at Parser.block (/usr/local/lib/node_modules/stylus/lib/parser.js:753:21)
    at Parser …
Run Code Online (Sandbox Code Playgroud)

stylus indentation parse-error

2
推荐指数
1
解决办法
3015
查看次数

路由错误:错误:发送后无法设置标头

好吧,在我阅读了很多有关此问题的帖子后,我开始停滞不前.这个错误很受欢迎Error: Can't set headers after they are sent.

最好的答案在这里,但是,我没有重复的功能或两次执行的回调(至少不是我知道的),它只是一个标准的基础休息API.

完整跟踪日志:

/home/nano/Dev/JS/OMI/node_modules/mongoose/lib/utils.js:413
        throw err;
              ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
    at ServerResponse.header (/home/nano/Dev/JS/OMI/node_modules/express/lib/response.js:666:10)
    at ServerResponse.send (/home/nano/Dev/JS/OMI/node_modules/express/lib/response.js:146:12)
    at ServerResponse.json (/home/nano/Dev/JS/OMI/node_modules/express/lib/response.js:235:15)
    at Promise.<anonymous> (/home/nano/Dev/JS/OMI/app/routes/clientes.js:19:11)
    at Promise.<anonymous> (/home/nano/Dev/JS/OMI/node_modules/mongoose/node_modules/mpromise/lib/promise.js:172:8)
    at Promise.emit (events.js:95:17)
    at Promise.emit (/home/nano/Dev/JS/OMI/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
    at Promise.reject (/home/nano/Dev/JS/OMI/node_modules/mongoose/node_modules/mpromise/lib/promise.js:111:15)
    at Promise.error (/home/nano/Dev/JS/OMI/node_modules/mongoose/lib/promise.js:95:15)
Run Code Online (Sandbox Code Playgroud)

无论如何,我的代码很简单:

index.js:

"use strict";

var express = require('express'),
    router  = express.Router();

var clientes = require('./clientes');
var items    = require('./items');

router.route('/clientes')
  .post(clientes.crear)
  .put(clientes.actualizar)
  .delete(clientes.borrar);

router.route('./items') …
Run Code Online (Sandbox Code Playgroud)

javascript node.js express

2
推荐指数
1
解决办法
8119
查看次数

如果rethinkdb中需要,请创建数据库

这是我与rethinkdb的第一次互动,它看起来不错,但我遇到了一些问题......

这个想法很简单:如果尚未创建数据库,则创建数据库.

代码很简单,或者很好,代码的概念:

module.exports = function(r, config) {
  var connection = null;

  r.connect(config.rdb, function(err, conn) {
    if (err) throw err
      connection = conn;
  });

  r.dbList()
    .contains('semestres')
    .do(function(dbExists) {
      return r.branch(
        dbExists,
        { created: 0 },
        r.dbCreate('semestres')
      );
    })
    .run(connection, function(err) {
      if (err) throw err;
    });
};
Run Code Online (Sandbox Code Playgroud)

因此,这只是创建一个连接并指定与变量的连接,然后检查数据库是否存在"semestres",如果它存在,它什么都不做,否则,创建它.

但不是,我在运行服务器时遇到此错误:

Unhandled rejection RqlDriverError: First argument to `run` must be an open connection.
    at new RqlDriverError (/home/nano/Dev/semestres/node_modules/rethinkdb/errors.js:14:13)
    at FunCall.TermBase.run (/home/nano/Dev/semestres/node_modules/rethinkdb/ast.js:129:29)
    at module.exports (/home/nano/Dev/semestres/config/database.js:20:6)
    at Object.<anonymous> (/home/nano/Dev/semestres/server.js:10:29)
    at Module._compile (module.js:428:26)
    at Object.Module._extensions..js (module.js:446:10) …
Run Code Online (Sandbox Code Playgroud)

javascript node.js rethinkdb

2
推荐指数
1
解决办法
1593
查看次数

验证nodejs + express中的URL以处理错误的请求错误

那么,在阅读了关于这个问题的一些事情之后,我决定询问一下.

核心思想很简单:检测传入的无效URL/URI,并使用相关代码/数据向客户端返回响应.

通常,在处理节点中的错误时,我们使用如下语法:

if (err) {
    return res.status(500).json(error: {msg: err.message, stack: err.stack});
}
Run Code Online (Sandbox Code Playgroud)

好吧,这很简单,但重要的是我们检测到:"嘿,如果发生错误,请将此事发送给客户".

但如果它不是500内部怎么办?据我所知,错误的请求错误会像客户端错误一样发送,并在提示符,rigth中有自己的堆栈,类型和消息?

读取这个,我找到了URIError构造函数,它指向一个表示与ivalids URI一起出现的错误的实例.所以,有可能这样做:

if (err instanceof URIError) { /* send a handler for bad request */ };
Run Code Online (Sandbox Code Playgroud)

或者我需要从头开始验证URI并进行自己的错误继承?

任何提示?理念?... 提前致谢!<3

javascript rest http node.js

1
推荐指数
1
解决办法
3658
查看次数

gulp-concat内容的两倍

这对我来说是一个奇怪的事情,我有一个任务是连接我的.js文件,然后用观察者对它们进行uglify,但concat任务只是每次调用内容的两倍......

这是我的gulpfile:

'use strict';

let gulp        = require('gulp');
let stylus      = require('gulp-stylus');
let sourcemaps  = require('gulp-sourcemaps');
let concat      = require('gulp-concat');
let uglify      = require('gulp-uglify');
let plumber     = require('gulp-plumber');
let bootstrap   = require('bootstrap-styl');
let rupture     = require('rupture');
let copy        = require('gulp-copy2');

/*
  Prepare the paths
*/
let base = './theme';
let themeName = 'own-theme';

let paths = {
  stylus    : `${base}/${themeName}/css`,
  js        : `${base}/${themeName}/js`,
  vendor    : `${base}/${themeName}/js/vendor`
}

/*
  Stylus compile
*/
gulp.task('stylus-compile', () => {
  return …
Run Code Online (Sandbox Code Playgroud)

javascript gulp

1
推荐指数
1
解决办法
819
查看次数

bootstrap-sass + gulp:媒体查询表达式必须以'(''开头

我在这里遇到了bootstrap-sass的问题.我正在尝试通过Gulp和我的style.scss文件中的一些其他scss库编译bootstrap ,但它会抛出这个错误:

Message:
    css/dev/style.scss
Error: media query expression must begin with '('
        on line 1 of css/dev/style.scss
>> @import 'breakpoint-slicer'
   ---------------------------^

Details:
    formatted: Error: media query expression must begin with '('
        on line 1 of css/dev/style.scss
>> @import 'breakpoint-slicer'
   ---------------------------^

    column: 28
    line: 1
    file: /home/nano/Sandbox/bolt-seed/theme/own-theme/css/dev/style.scss
    status: 1
    messageFormatted: css/dev/style.scss
Error: media query expression must begin with '('
        on line 1 of css/dev/style.scss
>> @import 'breakpoint-slicer'
   ---------------------------^
messageOriginal: media query expression must begin with '(' relativePath: css/dev/style.scss
Run Code Online (Sandbox Code Playgroud)

我只是 …

sass twitter-bootstrap gulp gulp-sass

1
推荐指数
2
解决办法
2635
查看次数

SyntaxError:位于1的JSON中的意外标记'

是的,我知道这里的问题是一个糟糕的格式化JSON,但我读了很多问题,整个JSON字符串甚至所有这些,我无法弄清楚问题本身.

我从服务器获取json字符串响应并尝试解析json.parse(string)但总是得到相同的错误:

未捕获的SyntaxError:位于JSON.parse()的位置1的JSON中的意外标记:1:6

有人可以帮我这个吗?我看不出问题.

这是原始字符串格式化:

"{'0': [{'text': 'conquistar', 'value': 1559.0}, {'text': 'mujer', 'value': 1559.0}, {'text': 'no', 'value': 866.0}, {'text': 'olvidar', 'value': 842.0}, {'text': 'libros', 'value': 842.0}, {'text': 'últimos', 'value': 645.0}, {'text': 'imdb', 'value': 645.0}, {'text': 'años', 'value': 645.0}, {'text': 'encontrarás', 'value': 519.0}, {'text': 'donde', 'value': 519.0}, {'text': 'páginas', 'value': 519.0}, {'text': 'tatuaje', 'value': 519.0}, {'text': 'sabías', 'value': 481.0}, {'text': 'potter', 'value': 481.0}, {'text': 'universo', 'value': 481.0}, {'text': 'harry', 'value': 481.0}, {'text': 'del', 'value': 481.0}, {'text': 'datos', 'value': 481.0}, …

javascript json

1
推荐指数
2
解决办法
7798
查看次数

快速路由器中间件:参考错误“req 未定义”

我正在使用一个对令牌进行身份验证的中间件,但问题不是代码片段,当我实例化函数时,问题就出现了。

有我的代码:

router.use(authRequirer(req, res, next));
Run Code Online (Sandbox Code Playgroud)

当然,这是路由文件:

let router = express.Router();

// Middleware
import authRequirer from '../util/authRequirer';

// Controllers
import AuthCtrl from '../controllers/authCtrl';
import UserCtrl from '../controllers/userCtrl';

let authCtrl = new AuthCtrl();
let userCtrl = new UserCtrl();

router.get('/', (req, res) => {
  res.json({ message: "Hey, im working" });
});

// Login, Register, setup admin
router.get('/setup'    , authCtrl.setup);
router.post('/register', authCtrl.register);
router.post('/login'   , authCtrl.login);

// Autenticacion requerida
router.use(authRequirer(req, res, next));

router.route('/users')
  .get(userCtrl.getAll)
  .post(userCtrl.create);

router.route('/users/:username')
  .get(userCtrl.getOne)
  .put(userCtrl.edit)
  .delete(userCtrl.delete);

export default router;
Run Code Online (Sandbox Code Playgroud)

我认为我没有做任何不正常的事情,但是当我运行代码时,它会向我抛出以下跟踪:

/home/nano/Dev/omgfriki-api/app/routes/apiroutes.js:44
router.use((0, …
Run Code Online (Sandbox Code Playgroud)

node.js express

0
推荐指数
1
解决办法
5616
查看次数

找到Webpack配置文件但未配置任何条目

我试图为我的个人项目组织一个webpack 2模板,webpack-dev-server并使用npm命令运行它,但我收到此错误:

Configuration file found but no entry configured.

这很奇怪,因为条目是定义的,我测试了解析的路线,没关系,所以这里是我的webpack配置,运行它的命令和配置加载器的文件:

webpack.config.dev.js

const path       = require('path');
const fs         = require('fs');
const configs    = require('./dev-wpk-conf');
const HtmlPlugin = require('html-webpack-plugin');
const Dotenv     = require('dotenv-webpack');
const webpack    = require('webpack');
const dirPath    = fs.realpathSync(process.cwd());

const config = {
  entry: {
    bundle: path.resolve(dirPath, '../src/index.js'),
    vendor: configs.vendor
  },
  output: {
    path: path.resolve(dirPath, '../dist'),
    filename: '[name].[hash].js'
  },
  devServer: {
    port: 3030
  },
  module: {
    rules: [
      configs.jsonLoader,
      configs.babelLoader,
      configs.imgLoader,
      configs.sassLoader
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({ …
Run Code Online (Sandbox Code Playgroud)

node.js webpack webpack-dev-server

0
推荐指数
1
解决办法
9391
查看次数