Unexpected token < Error not going - reactjs

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.

Related

Axios post error

I am trying to post to my api endpint, I get the error:
Uncaught (in promise) Error: Network Error
at createError (C:\sites\LYD\node_modules\axios\lib\core\createError.js:16)
at XMLHttpRequest.handleError (C:\sites\LYD\node_modules\axios\lib\adapters\xhr.js:87)
My axios post is:
submitForm(UserDetails) {
let self = this;
self.show();
axios
.post('http://localhost:3001/api/users', UserDetails)
.then(function(response) {
self.hide();
});
}
My node error is:
C:\sites\LYD>node server
api running on port 3001
(node:11808) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
events.js:160
throw er; // Unhandled 'error' event
^
TypeError: First argument must be a string or Buffer
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:555:11)
at C:\sites\LYD\server\index.js:75:20
at C:\sites\LYD\node_modules\mongoose\lib\model.js:3809:16
at C:\sites\LYD\node_modules\mongoose\lib\services\model\applyHooks.js:164:17
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
Any ideas?
My server.js is:
//first we import our dependencies...
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('../models/users');
//and create our instances
const app = express();
const router = express.Router();
//set our port to either a predetermined port number if you have set it up, or 3001
const port = process.env.API_PORT || 3001;
//db config -- REPLACE USERNAME/PASSWORD/DATABASE WITH YOUR OWN FROM MLAB!
const mongoDB =
'mongodb://dxxx#aws-eu-west-1-portal.4.dblayer.com:10204/xxx?ssl=true';
mongoose.connect(mongoDB, { useMongoClient: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//now we should configure the APi to use bodyParser and look for JSON data in the body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//To prevent errors from Cross Origin Resource Sharing, we will set our headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader(
'Access-Control-Allow-Methods',
'GET,HEAD,OPTIONS,POST,PUT,DELETE'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
//and remove cacheing so we get the most recent comments
res.setHeader('Cache-Control', 'no-cache');
next();
});
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!' });
});
//adding the /comments route to our /api router
router
.route('/users')
//retrieve all comments from the database
.get(function(req, res) {
//looks at our Comment Schema
User.find(function(err, users) {
if (err) res.send(err);
//responds with a json object of our database comments.
res.json(users);
});
})
//post new comment to the database
.post(function(req, res) {
var NewUser = new User();
req.body.accessCode ? (NewUser.accessCode = req.body.accessCode) : null;
req.body.age ? (NewUser.age = req.body.age) : null;
req.body.drinkConcern
? (NewUser.drinkConcern = req.body.drinkConcern)
: null;
req.body.drinkOften ? (NewUser.drinkOften = req.body.drinkOften) : null;
req.body.ethnicity ? (NewUser.ethnicity = req.body.ethnicity) : null;
req.body.gender ? (NewUser.age = req.body.gender) : null;
req.body.language ? (NewUser.language = req.body.language) : null;
NewUser.save(function(err) {
if (err) res.end(err);
res.json({ message: 'Comment successfully added!' });
});
});
//Adding a route to a specific comment based on the database ID
router
.route('/users/:id')
//The put method gives us the chance to update our comment based on the ID passed to the route
.put(function(req, res) {
Comment.findById(req.params.id, function(err, user) {
if (err) res.send(err);
//setting the new author and text to whatever was changed. If nothing was changed
// we will not alter the field.
req.body.author ? (comment.author = req.body.author) : null;
req.body.text ? (comment.text = req.body.text) : null;
//save comment
user.save(function(err) {
if (err) res.send(err);
res.json({ message: 'Comment has been updated' });
});
});
})
//delete method for removing a comment from our database
.delete(function(req, res) {
//selects the comment by its ID, then removes it.
User.remove({ _id: req.params.comment_id }, function(err, user) {
if (err) res.send(err);
res.json({ message: 'Comment has been deleted' });
});
});
//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
I have changed my axios post to this:
let self = this;
self.show();
const headers = {
'Content-Type': 'application/json',
};
axios
.post('http://localhost:3001/api/users', UserDetails, headers)
.then(function(response) {
self.hide();
});
You can change the mongoose query to,
let query = {} //or any other query
User.find(query,function(err,res){
...
})
I think the problem is with your routes.
When you create a route instead of using router.route('/route').post(function(req, res) { ... }, use router.post('/route', function(req, res) { .... } (obviously change .post to the method you want to use)
In your code this would be:
router
.get('/users', function(req, res) {
User.find(function(err, users) {
if (err) res.send(err);
res.json(users);
});
})
I think you can only do app.route('/route').get(...).post(...) but not with router
Look at the express routing documentation for more info: https://expressjs.com/en/guide/routing.html

How to enable CORS on node js?

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.

HTTP requests fail for AngularJS/Express using Mongoose when it works with MongoJS

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

XMLHttpRequest cannot load [url] Response for preflight is invalid (redirect)

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

BackboneJS .get() and .at() undefined after .fetch()

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"));
}
});

Resources