localhost:3000
[{"idrooms":1,"roomname":"red","occupants":0}, {"idrooms":2,"roomname":"green","occupants":0},{"idrooms":3,"roomname":"blue","occupants":0}, {"idrooms":4,"roomname":"yellow","occupants":0}, {"idrooms":5,"roomname":"purple","occupants":0},{"idrooms":6,"roomname":"cyan","occupants":0}]
On the client side I started with the basics I know so far:
Title
<script src="jslib/jquery.js"></script>
<script src="jslib/underscore.js"></script>
<script src="jslib/backbone.js"></script>
<script>
// Your code goes here
var Room = Backbone.Model.extend({
defaults: {
idrooms: 0,
roomname: "default",
occupants: 0
}
});
var RoomList = Backbone.Collection.extend({
model: Room,
url: 'http://localhost:3000'
});
var roomlist = new RoomList();
roomlist.fetch();
console.log(roomlist);
console.log(roomlist.at(1));
console.log(roomlist.get(1));
</script>
</body>
</html>
There is all kind of data in roomlist and if I drill into it I see the attributes of all six Room model objects. roomlist.at(1) and roomlist.get(1) are returning an undefined. Perhaps I made a mistake somewhere.
The server is short enough perhaps I should post it:
var express = require('express')
, cors = require('cors')
, get = require('./routes/get')
, http = require('http')
, path = require('path')
, mysql = require('mysql')
, app = express();
var connection = mysql.createConnection({ host: 'localhost', user: 'root',
password: 'oilwell123', database: 'multiroomchat'});
app.get('/', cors(), function(req, res, next){
if (connection) {
connection.query('select * from rooms', function(err, rows, fields) {
if (err) throw err;
res.contentType('application/json');
//res.write(JSON.stringify(rows));
res.send(rows);
res.end();
});
}
});
app.listen(3000, function(){
console.log('CORS-enabled web server listening on port 80');
});
jsonlint says its valid json...
Thank you for posting...
The fetch method is asynchronous, so the output variable won't have been assigned by the time you use it.
Try this.
roomlist.fetch({
success : function(collection, respone) {
console.log(collection);
console.log("collection.at(1)", collection.at(1));
console.log("collection.get(c0)", collection.get("c0"));
}
});
Related
I am having a problem that I don't really understand. I have a node js server that server simple index.html page (This is actually angular). My server code looks like this:
var express = require('express');
var app = express();
var cors = require('cors')
var port = 4000;
var path = require("path");
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.static('.'))
console.log(__dirname + '/.');
app.use(cors({
origin: true,
credentials: true
}));
app.get("/", function(res, req){
req.sendFile(path.join('/index.html'));
});
app.listen(port,'0.0.0.0' , function(){
console.log("listening on * "+ port);
});
I my html page, I have and angularjs service that is accessing localhost:7000 and socket.io that is accessing localhost:7000.
My service look like this :
if(param){
$scope.isloading = true;
$http.post(
'http://' + $location.host() + ':7000/container',
{ "method": "start", "nomber": param } ,
{}
).then(function(err, data){
console.log("No error : ");
console.log(data);
if (err){
console.log(err);
}
$scope.isloading = false;
console.log("end Loading" + $scope.isloading);
}, function(err, data){
$scope.isloading = false;
console.log("error ");
});
}
and the html call to socket.io is this :
<script>var socket = io.connect('http://localhost:7000');
socket.on("news", function(data){
console.log(data);
});</script>
my problem is that I am unable to allow the angular service and socket.io call at the same time. I have installed CORS on chrome. when I enable it, socket.io don't work, but service works.. When I disable it service don't work and socket.io does: . Can you please help me to find a solution ?
Update
I have tried many of the solution proposed here. But they don't work for me.
Try like this,
app.use(cors({
origin: function (origin, callback) {
var allowed = ['http://localhost:7000'].indexOf((origin || '').toLowerCase()) !== -1;
callback(null, allowed);
}
}));
Since the error message says:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin'
header when the credentials flag is true
Why don't you try setting your origin instead?
I would use the following middleware:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4000");
next();
});
This is assuming that the credentials flag is absolutely necessary.
Its been 3 hours banging my head , but still i cant find what the error is , I am getting an error "Stack trace: SyntaxError: Unexpected token <". I have nearly tried all sort of solutions from stack overflow itself but nothing seems to work . So Plz help me out.
var argv = require('yargs')
.option('p', {
alias: 'port',
description: 'Specify the server\'s port',
default: 9009
})
.option('a', {
alias: 'address',
description: 'Specify the server\'s address',
default: '127.0.0.1'
})
.help('h').alias('h', 'help')
.strict()
.argv;
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var reactRender = require('react-render');
// Ensure support for loading files that contain ES6+7 & JSX
require('babel-core/register')({
presets:["es2015","react"]
});
var ADDRESS = argv.address;
var PORT = argv.port;
var app = express();
var server = http.Server(app);
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.end('React render server');
});
app.post('/render', function(req, res) {
reactRender(req.body, function(err, markup) {
if (err) {
res.json({
error: {
type: err.constructor.name,
message: err.message,
stack: err.stack
},
markup: null
});
} else {
res.json({
error: null,
markup: markup
});
}
});
});
server.listen(PORT, ADDRESS, function() {
console.log('React render server listening at http://' + ADDRESS + ':' + PORT);
});
I am using browserify with React. Any help will be appreciated.
It sounds like your ajax call is returning HTML instead of JSON (perhaps because you're getting an error page) so your res.json is seeing the beginning of the page as <html>... and erroring. Try logging the response and looking at it to make sure it's legit JSON.
Need some help figuring out whats wrong with my code that's giving me 500 internal server error. Have been trying to figure out root cause myself since last 3 days to no avail. I've started learning the MEAN stack and have been experimenting with MongoJs and Mongoose. It's the latter setup that is not working. I've pasted below
a) gulpfile.js
b) Mongoose model/schema file (modelA.js),
c) httprequests.js file containing http requests using mongojs and mongoose {on the sideline - is it a bad idea to have MongoJS and Mongoose codes in the same application???} and
d) angular script file (phone.js) . With the current coding my page (not mentioned below) using mongojs is working perfectly.
e) Error messages from Terminal and Chrome console
I'm new to MEAN and must be doing something basically wrong. Any help is sincerely appreciated.
Gulpfile.js:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
// historyapifallback to help overcome page refersh issue in angularjs
var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
browserSync.init({
port: 3001,
proxy: {
target: "localhost:3000",
ws: true,
middleware: [ historyApiFallback() ]
}
});
gulp.watch("./**/*.*").on('change', browserSync.reload);
});
gulp.task('default',['serve'], function() {
var httpRequests = require('./scripts/mongo-mongodb/httprequests');
});
modelA.js
var mongoose = require('../../../node_modules/mongoose/lib');
var Schema = mongoose.Schema;
var phoneSchema = new Schema({
age : Number,
carrier : String,
id : String,
imageUrl : String,
name : String,
company: String,
snippet : String
});
/* global db */
module.exports = mongoose.model('Phone', phoneSchema);
httprequests.js
// load express module
var express = require("express");
// bootstrap express
var app = express();
//serve up index.html
app.use(express.static("./"));
// body parser for post requests
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Mongojs codes follows...
var mongojs = require('mongojs');
var db = mongojs('test',['technology']);
// get all data from db
app.get('/techstack',function(req,res) {
db.technology.find({},function(err,docs) {
if (err) throw err;
// console.log("im here");
// console.log(docs);
res.json(docs);
});
});
// get data from db for specific id
app.get('/techstack/:id',function(req,res) {
var id = req.params.id;
db.technology.findOne({_id: mongojs.ObjectId(id)},function(err,docs) {
if (err) console.error;
console.log(id);
console.log("gulpfile");
res.json(docs);
});
});
app.post('/techstack', function(req,res) {
console.log(req.body);
db.technology.insert(req.body,function(err,docs) {
if (err) console.error;
res.json(docs);
});
});
app.delete('/techstack/:id', function(req,res) {
var id = req.params.id;
db.technology.remove({_id: mongojs.ObjectId(id)},function(err,docs) {
// console.log(id);
// db.technology.remove({ _id: id},function(err,docs) {
if (err) console.error;
res.json(docs);
});
});
app.put('/techstack/:id', function(req,res) {
var id = req.params.id;
db.technology.findAndModify(
{
query: {_id:mongojs.ObjectId(id)},
update: {$set: {sl:req.body.sl, name:req.body.name, status:req.body.status, complexity:req.body.complexity}},
new: true
}, function (err, docs) {
if (err) console.error;
res.json(docs);
});
});
//
// Mongoose codes follow...
var mongoose = require('../../../node_modules/mongoose/lib');
mongoose.connect('mongodb://localhost/mean_db');
// var uri ='mongodb://localhost/mean_db';
// global.db = mongoose.createConnection(uri);
// var routes = require('../mongo-mongoose/routes');
var Phone = require('./modelA');
var router = express.Router(); // get an instance of the express Router
// // 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) {
Phone.find({},function(err, docs) {
if (err)
res.send(err);
res.send(docs);
});
});
router.post('/',function(req, res) {
var phone = new Phone(); // create a new instance of the Phone model
// save the phone and check for errors
phone.save(req.body,function(err,docs) {
if (err)
res.send(err);
res.json(docs);
});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /phone-list
app.use('/phone-list', router);
app.listen(3000);
console.log('Listening on port 3000');
phone.js
'use strict';
var phone = angular.module('phone',[]);
phone.controller('View1Ctrl', function($scope,$http,$log,$location) {
$scope.phone = {
age : 0,
carrier : "",
id : "",
imageUrl : "",
name : "",
company: "",
snippet : ""
};
$http.get('/phone-list')
.then(function (response) {
// console.log(response.data);
$scope.phoneList = response.data;
}
);
$scope.insertPhone = function () {
$http.post('/phone-list', $scope.phone)
.then(function (response) {
console.log("inside post in phone.js");
$scope.phoneList = response.data;
$route.reload();
});
};
Error Messages:
On terminal
14:18:51] Using gulpfile ~/github/mean-project/app/gulpfile.js
[14:18:51] Starting 'serve'...
[14:18:52] Finished 'serve' after 129 ms
[14:18:52] Starting 'default'...
Listening on port 3000
[14:18:52] Finished 'default' after 686 ms
[BS] Proxying: http://localhost:3000
[BS] Access URLs:
----------------------------------
Local: http://localhost:3001
External: http://10.0.1.12:3001
----------------------------------
UI: http://localhost:3003
UI External: http://10.0.1.12:3003
----------------------------------
Something is happening.
Something is happening.
Something is happening.
Something is happening.
Something is happening.
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^ TypeError: callback is not a function
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/lib/model.js:228:5
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/lib/model.js:135:7
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/collection.js:504:5
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/collection.js:666:5
at handleCallback (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:473:9
at handleCallback (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at resultHandler (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:420:5)
at commandCallback (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1194:9)
at Callbacks.emit (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at null.messageHandler (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:358:23)
at Socket.<anonymous> (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:292:22)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
On browser console
angular.js:12011 POST http://localhost:3001/phone-list net::ERR_EMPTY_RESPONSE
(anonymous function) # angular.js:12011
n # angular.js:11776
(anonymous function) # angular.js:11571
(anonymous function) # angular.js:16383
$eval # angular.js:17682
$digest # angular.js:17495
$delegate.__proto__.$digest # VM95:844
$apply # angular.js:17790
$delegate.__proto__.$apply # VM95:855
(anonymous function) # angular.js:25890
Sf # angular.js:3497
d # angular.js:3485
I am having a 404 issue with my NodeJS API. I don't know if I am quite doing it right, I tried referring to documentation, and I feel like it's close.
MongoDB Schema
var User = mongoose.Schema({
local: {
email: String,
password: String,
handle: String,
pic: {data: Buffer, contentType: String}
}
});
NodeJS UPDATE API
app.post('/api/users', function(req, res, user) {
User.update({email : user.email,
password : user.password,
handle : user.handle,
pic : user.pic},
{$set: {
email : req.body.email,
password : req.body.email,
handle : req.body.handle,
pic : req.body.pic,
done : false
}
}, function(err, users) {
if(err) {
res.send(err);
}
res.redirect('/profile');
});
});
Controller POST API call
$scope.editProfile = function() {
$http.post('/api/users', $scope.editFormData)
.success(function(data) {
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Any suggestions?
You are not doing a post call correct. You can't pass your post object in the URL. Your node post should look like this.
app.post('/api', upload.array(), function(req, res) {
var body = req.body; //body will be your post object
});
For a post to work you need to make sure you have the proper things added to your Node Project. The above example is using ExpressJS with require('body-parser') and require('multer'). The example you are showing will never show as a true path. For reference here is how you would do a get in node.
app.get('/getcall/*', function(){
// the * denotes any singleton parameter you wanted to pass in.
})
Here are the references I use in all my node projects. These are the basics.
var express = require('express'),
bodyParser = require('body-parser'),
multer = require('multer'),
helmet = require('helmet'),
upload = multer(),
path = require('path'),
request = require('request'),
app = express(),
http = require('http');
Also as for your angular call an $http.post looks like this and you should be using .then instead of .success.
$http.post('/api', $scope.editFormData)
.then(function successCallback(resp) {
console.log(resp.data)
}, function errorCallback(resp) {
console.log(resp)
});
I'm making an ionic app for android and today I implemented a server side nodejs (express) Restful API with mongodb on cloud9.
But when I trigger a http request to the url, I keep getting the error mentioned in the title:
This is my angular http request on ionic (simply to test first):
app.controller('DashCtrl', function($scope, $http, $q) {
$http.get('https://[workspace]-[user].c9users.io/api/capture')
.then(function(result) {
console.log(result);
});
});
This is an image of my workspace:
I used the following code to make the database:
api.js
var Capture = require('../models/capture');
module.exports = function(router) {
router.get('/capture', function(req, res){
var capture = new Capture();
// capture.birdname = req.body.birdname;
// capture.place.city = req.place.body.city;
// capture.place.country = req.place.body.country;
capture.birdname = "Pigeon";
capture.save(function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.get('/captures', function(req, res){
Customer.find({}, function(err, data){
res.json(data);
})
})
}
capture.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var captureSchema = mongoose.Schema({
birdname: String,
place: {
city: String,
country: String
}
});
module.exports = mongoose.model('Capture', captureSchema)
database.js
module.exports = {
'url': 'mongodb://' + process.env.IP
}
server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var configDB = require('./server/config/database.js');
mongoose.connect(configDB.url);
var api = express.Router();
require('./server/routes/api')(api);
app.use('/api', api);
app.listen(process.env.PORT, process.env.IP);
console.log('Listening on port ' + process.env.PORT)
Anyone have an idea why I'm getting this error and what I need to do to fix this?
I'm guessing it has something to do with the server allowing me to send requests to the API though I don't know how to implement that.
Is there also a way to secure my database (API key maybe) and how would I implement this?
Thanks in advance