- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我们正在开发一个应用程序,我们将 Firebase 用作数据库,并表示为中间件/后端,用于路由我们在 Reactjs 中开发的前端所使用的 RESTful API。
下面是我们的 server.js 文件的样子:
var express = require('express');
var app = express();
//Used for getting POST variables from forms as well as query parameters
var bodyParser = require('body-parser');
var validator = require('express-validator');
//Contains all the routes
var routes = require('./routes/routes');
var path = require('path');
//Used for serving jade files
app.set('view engine', 'jade');
//For serving static resources like scripts, styleSheets, html
app.use(express.static(__dirname + '/views'));
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET");
next();
});
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(validator({
customValidators: {
onlyAlphabets: function(value) {
if (value.match('^[a-zA-Z ]*$')) {
return true;
} else {
return false;
}
},
password: function(value) {
if (value.length >= 6 && value.length <=25 && value.match('^[\x20-\x7F]*$')) {
return true;
} else {
return false;
}
}
}
}));
app.use(routes);
var port = process.env.PORT || 8080; //Set our port
app.listen(port);
console.log('Magic happens on port ' + port);
下面是 route.js 中的路由代码:
var express = require('express');
var views = __dirname;
// Node.js path library - https://nodejs.org/api/path.html
var path = require('path');
var Firebase = require("firebase");
var myFirebaseRef = new Firebase("https://crackling-inferno-8454.firebaseio.com/vendor_details");
var router = express.Router();
//Password Encryption and decryption helpers
var hashFunction = require('../helpers/encrypt');
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function(req, res) {
res.render('vendor_form');
});
router.route('/get_vendors').get(function(request, response) {
myFirebaseRef.on("value", function(snapshot) {
var store = snapshot.val();
// Looping to get the firebaseId generated while push
for(var key in store){
store[key].id = key; // Store firebaseID generated during push to store in JSON object
}
response.send(Object.keys(store).map(function(k) { return store[k]; }));
}, function (errorObject) {
response.send("The read failed: " + errorObject.code);
});
});
router.route('/post_vendor').post(function(request, response) {
request.checkBody({
'vendor_name': {
notEmpty : {
errorMessage: 'Please enter a vendor\'s name'
},
onlyAlphabets : {
errorMessage: 'Please enter only alphabets'
}
},
'enterprise_name': {
notEmpty : {
errorMessage: 'Please enter an enterprise\'s name'
},
onlyAlphabets : {
errorMessage: 'Please enter only alphabets'
}
},
'vendor_email': {
notEmpty : {
errorMessage: 'Please enter your email address'
},
isEmail : {
errorMessage: 'please enter an appropriate email format'
}
},
'vendor_password': {
notEmpty : {
errorMessage: 'Please enter a password'
},
password: {
errorMessage: 'Password length should be between 6-25 characters'
}
},
'food_preference': {
notEmpty: {
errorMessage: 'You must select atleast one food preference'
}
}
});
var errors = request.validationErrors();
// var onComplete = function(error) {
// if (error) {
// response.send('Failed to add stats to the database');
// return false;
// } else {
// // response.render('vendor_form', { success: true });
// response.send('Success');
// return true;
// }
// };
if (errors) {
response.send(errors);
// response.render('vendor_form', { error: errors });
return false;
} else {
myFirebaseRef.push().set({
'id': Firebase.ServerValue.TIMESTAMP,
'vendor_name': request.body.vendor_name,
'enterprise_name': request.body.enterprise_name,
'vendor_email': request.body.vendor_email,
'vendor_password': hashFunction.encrypt(request.body.vendor_password),
'food_preference': request.body.food_preference
}, function(err) {
if (err) {
response.send('Failed to add stats to the database');
} else {
response.send('Success');
}
});
return true;
}
});
module.exports = router;
下面是我们在前端添加的用于发布数据的代码。我们也在使用 whatwg-fetch 包:
httpservice.js:
var Fetch = require('whatwg-fetch');
var baseUrl = 'http://192.168.1.134:8080';
var Service = {
get: function(url) {
console.log('MAKING A GET REQUEST');
return fetch(baseUrl + url)
.then(function(response) {
return response.json();
});
},
post: function(url, postData) {
console.log('MAKING A POST REQUEST');
return fetch(baseUrl + url, {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(postData)
}).then(function(response) {
return response;
});
}
}
module.exports = Service;
VendorForm.js(React 组件文件)
HTTP.post('/post_vendor', httpRequestBody)
.then(function(response) {
console.log(response);
}.bind(this));
我们通过 nodemon 启动我们的服务器,它提供在 FIREBASE + EXPRESS 中开发的 RESTful API。这是我们在发布以下内容时收到的错误:
FIREBASE WARNING: Exception was thrown by user callback. Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:163:12)
at ServerResponse.json (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:249:15)
at ServerResponse.send (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:151:21)
at /var/www/tutorials/express_firebase/routes/routes.js:30:12
at /var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:200:710
at ec (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:52:165)
at ac (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:31:216)
at bc (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:30:1259)
at Ji.h.Mb (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:220:440)
at X.set (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:256:335)
at /var/www/tutorials/express_firebase/routes/routes.js:96:24
at Layer.handle [as handle_request] (/var/www/tutorials/express_firebase/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/tutorials/express_firebase/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/var/www/tutorials/express_firebase/node_modules/express/lib/router/route.js:112:3)
/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:52
(d="0"+d),c+=d;return c.toLowerCase()}var zd=/^-?\d{1,10}$/;function td(a){return zd.test(a)&&(a=Number(a),-2147483648<=a&&2147483647>=a)?a:null}function ec(a){try{a()}catch(b){setTimeout(function(){R("Exception was thrown by user callback.",b.stack||"");throw b;},Math.floor(0))}}function S(a,b){if(t(a)){var c=Array.prototype.slice.call(arguments,1).slice();ec(function(){a.apply(null,c)})}};function Ad(a){var b={},c={},d={},e="";try{var f=a.split("."),b=Pb(id(f[0])||""),c=Pb(id(f[1])||""),e=f[2],d=c.d||{};delete c.d}catch(g){}return{oh:b,Dc:c,data:d,ah:e}}function Bd(a){a=Ad(a).Dc;return"object"===typeof a&&a.hasOwnProperty("iat")?z(a,"iat"):null}function Cd(a){a=Ad(a);var b=a.Dc;return!!a.ah&&!!b&&"object"===typeof b&&b.hasOwnProperty("iat")};function Dd(a){this.Y=a;this.g=a.n.g}function Ed(a,b,c,d){var e=[],f=[];Na(b,function(b){"child_changed"===b.type&&a.g.Ad(b.Le,b.Ma)&&f.push(new H("child_moved",b.Ma,b.Ya))});Fd(a,e,"chi
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:163:12)
at ServerResponse.json (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:249:15)
at ServerResponse.send (/var/www/tutorials/express_firebase/node_modules/express/lib/response.js:151:21)
at /var/www/tutorials/express_firebase/routes/routes.js:30:12
at /var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:200:710
at ec (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:52:165)
at ac (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:31:216)
at bc (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:30:1259)
at Ji.h.Mb (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:220:440)
at X.set (/var/www/tutorials/express_firebase/node_modules/firebase/lib/firebase-node.js:256:335)
at /var/www/tutorials/express_firebase/routes/routes.js:96:24
at Layer.handle [as handle_request] (/var/www/tutorials/express_firebase/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/tutorials/express_firebase/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/var/www/tutorials/express_firebase/node_modules/express/lib/router/route.js:112:3)
[nodemon] app crashed - waiting for file changes before starting...
根据错误,我们知道某些回调将 header 设置了两次,但不确定它是如何发生的。经历了几个堆栈溢出问题,但仍未找到解决方案。任何帮助,将不胜感激。感谢期待。
最佳答案
如果你看到你的堆栈跟踪
at /var/www/tutorials/express_firebase/routes/routes.js:30:12
文件route.js中的第30行
response.send(Object.keys(store).map(function(k) { return store[k]; }));
您需要更改on
方法一次
,否则每次数据更新时都会触发您的回调函数,
router.route('/get_vendors').get(function(request, response) {
myFirebaseRef.on("value", function(snapshot) {
当您调用 post 方法时破坏您的响应,因为 header 已在第 30 行发送。
参见引用资料 https://firebase.google.com/docs/database/server/retrieve-data#section-reading-once
基本上,您使用 once
方法所做的就是在读取值后立即删除回调。
关于node.js - FIREBASE 警告 : Exception was thrown by user callback. 错误:发送后无法设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507201/
你好,我正在尝试在 opensuse 中创建一个 Shell 脚本来创建 MySqlUsers,但是当我尝试运行它时,我得到了这个错误: Warning: Could not start progra
我阅读了有关此错误的所有信息,但未能找到任何解决方案。 我有一个看起来像这样的简单页面: $xmlfile = "/var/www/marees.xml"; //Fichier dans lequel
运行 Websphere App 服务器 V8.5 Liberty Profile。我找不到任何可以解决这些警告的帮助。我在 eclipse 。 ************** He
我尝试在 GC AppEngine 上部署应用程序。部署过程中没有错误,但应用程序无法运行(仅显示加载页面)。日志中唯一一个奇怪的原始 OpenBLAS WARNING - could not det
我刚开始学习 RestKit。我正在尝试使用它来使用 Foursquare api 获取附近的 field 。但每次我尝试“objectLoader:(RKObjectLoader *)objectL
我对 Vuejs 比较陌生,每次按键时都会收到以下警告: [Vue warn]: $attrs is readonly. found in ---> at src\component
Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external
我在尝试修改某些表时不断收到此错误。这是我的代码: /** = 1){ //$this->mysqli->autocommit(FALSE); //insert th
当我尝试使用 PHP 的 ftp_put 函数上传文件时,早些时候出现错误: 警告:ftp_put() [function.ftp-put]:无数据连接 现在,我尝试开启被动模式: ftp_pasv(
我一直在努力让这段代码适用于现阶段的年龄。它旨在计算一个范围内的素数,我已经编写了一种方法来打印它们。不幸的是,代码将无法编译,引用警告: “警告:[未检查] 未检查调用 add(E) 作为原始类型
尝试使用带有架构组件和Kotlin的Android Studio 3 Canary 5构建示例会给出此警告。 谁能告诉我原因? 谢谢,Ove 编辑#1: 这是Dan Lew前段时间制作的样本 http
我正在编写一个 Shiny 的应用程序,它运行得非常好,突然我收到两条警告消息。我已经回到以前运行良好的副本,它们现在显示相同的错误消息,所以我真的很困惑。我的代码仍然运行并在我 Shiny 的仪表板
03-25 05:52:15.329 8029-8042/com.mgh.radio W/MediaPlayerNative: info/warning (703, 0) 03-25 05:52:15
我在构建时在我的 gradle 控制台中收到一条警告消息: 警告:[options] 引导类路径未与 -source 1.7 一起设置 1 条警告 我怎样才能解决这个问题? 任何帮助表示赞赏! 最佳答
我有下一个代码: 测试.c #include "a1.h" int main() { int a = 8; foo(a); return a; } a1.h void foo
我的程序中有一个 WORD 变量。 WORD hour; 但是当我比较它的时候 if(hour>=0 && hour=0 && hour=0 的比较,它始终适用于 hour 是 WORD 类型,它是一
安全研究人员警告称,一个最新的严重的Java错误,其本质与目前在全球范围内利用的臭名昭著的 Log4Shell 漏洞相同 。 CVE-2021-42392 尚未在国家漏洞数据库 (NVD) 中
安装SqlServer2005时“版本变更检查 (警告)"问题排查 今天同事在安装SqlServer2005时遇到“版本变更检查 (警告) ”问题导致安装失败,警告提示如下: - 版本
我的 UWP 项目中出现以下警告。我已经标记了解决方案的示例,但我更感兴趣的是为什么在同一平台上创建另一个空项目时不会出现此警告? APPX4001: Build property AppxBundl
我试图修复我的登录脚本,在我的本地主机上它可以工作,但上传到我的在线测试服务器时,注销被破坏,我得到这个错误: Warning: session_destroy() [function.session
我是一名优秀的程序员,十分优秀!