I am developing an application with front end as angular and back end is node js, listing some values from database and send to node js .It shows some error like circular structure is there any way to override or any other option to response send back to my client side.
Node js server instance is :
app.post('/countrylist', function(req, res) {
var urlMataData = {
request : req,
responce:res
};
amqHandler.sendToAMQPServer(serialize.serialize(urlMataData),amqpConnection, 'countrylist' ,function(err,result){
console.log("callback value==>" + result)
});
amqHandler.reciveData(amqpConnection,'countrylist' ,function(err,data){
if(!err ){
console.log("am reciving request")
httpRequestHandler. makeHttpRequest(data,'countrylist', function(row){
console.log("CountryType==>"+ JSON.parse( row));
//res.json(row);
});
} else {
res.json(err);
}
});
});
Request handler is :
var countryList = function(req, res, next) {
query = 'SELECT id_country, country FROM edu.tbl_country';
database.getConnection(function (err, con) {
if(!err){
con.query(query, function(err,row) {
console.log("row type:"+ typeof row );
//res.contentType('application/json');
res.json(JSON.stringify(row));
});
}
});
};
Error
var body = JSON.stringify(val, replacer, spaces);
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at ServerResponse.json (/root/nodejsworkspace/EDU/rabitmq/node_modules/express/lib/response.js:228:19)
at ClientRequest.<anonymous> (/root/nodejsworkspace/EDU/rabitmq/AMQPServer.js:116:23)
at ClientRequest.g (events.js:273:16)
at emitOne (events.js:90:13)
at ClientRequest.emit (events.js:182:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:469:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:103:23)
at Socket.socketOnData (_http_client.js:359:20)
at emitOne (events.js:90:13)
Related
I am working on a basic auth middleware for a API it uses Node.js Mysql but if someone puts a incorrect key in auth header and sends the request the entire API crashes heres my code the issue is with the callback but I don't know how to fix that.
var express = require('express');
var app = express();
app.get('/', (request, response) => {
response.sendStatus(200);
});
let listener = app.listen(3000, () => {
console.log('Your app is currently listening on port: ' + listener.address().port);
});
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
database : 'systemdata'
});
connection.connect();
function systemAuth(apikey, callback)
{
connection.query('SELECT apikey FROM systemdata.systemkeys WHERE apikey = ?', [apikey], function(err, result)
{
if (err)
callback(err,null);
else
callback(null,result[0].apikey);
});
}
var auth = function (req, res, next) {
systemAuth(req.headers.apikey, function(err,data){
if (err) {
console.log("ERROR : ",err);
} else {
console.log("result from db is : ",data);
}
if(data == req.headers.apikey) {
next()
}else{
res.status(401).send({"error": "Missing or Invalid API-Key", "apikey": req.headers.apikey, "valid": "false"})
}
})
}
app.use(auth)
You will also have to check whether your result actually contains any rows.
A query not returning any rows is not an error, so err won't be set, if result is an empty array. And accessing an element by an index which does not exist leads to undefined, thus the error you are seeing.
function systemAuth(apikey, callback)
{
connection.query('SELECT apikey FROM systemdata.systemkeys WHERE apikey = ?', [apikey], function(err, result)
{
if (err) // some error with the query
callback(err,null);
else if (!result || result.length == 0) // no matching rows found
callback(new Error("invalid apikey"), null);
else // a matching row is found
callback(null,result[0].apikey);
});
}
I am working on an Express App with MongoDB and trying to utilize FeathersJS for all my services. Here I'm running a test try to get an error message from the server to the client, but I have an issue with the response from the error handler. My req headers have the correct application/json stuff, so I assumed the Error Handler should send valid json back.
I know I'm not using the next callback in my function, but when I try to do that it gives the same error, so I'm thinking it has to do with the Error Handler. Any direction here would be greatly appreciated!
The first error log is on the server, which is correct.
Bucket Services
error >>>>> Bucket validation failed
Possibly Unhandled Rejection: Bucket validation failed, Promise { <rejected> 'Bucket validation failed' }
>>>>>> Error: Unexpected token < in JSON at position 0
at convert (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/node_modules/feathers-errors/lib/index.js:365:79)
at toError (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/lib/client/base.js:24:37)
at process._tickCallback (internal/process/next_tick.js:103:7)
my create function within the BucketService class:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save((error) => {
console.log('error >>>>>', error.message);
if (error) { return Promise.reject(error.message); }
return Promise.resolve(new_bucket);
});
}
my router file:
const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const router = feathers();
const LoginService = require('../services/login_service');
const UserService = require('../services/user_service');
const BucketService = require('../services/bucket_service');
// Enable REST services
router.configure(rest());
router.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
router.use('/login', new LoginService());
router.use('/user', new UserService());
router.use('/bucket', new BucketService());
// Set up error handling
router.use(errorHandler());
module.exports = router;
I figured it out, the key was to correctly pass through a callback (next) function as the third parameter to handle errors. FeathersJS handles the Promise Rejections for you on errors. Then in my test I needed to convert the Feathers-Error to JSON before I could get the message.
I changed my test to:
it('can validate an incorrect bucket', (done) => {
const invalid_bucket = {
name: 'Invalid Bucket',
};
bucket_service.create(invalid_bucket, {}, (error) => {
error = error.toJSON();
assert(error.message.length > 0);
done();
});
});
and my create function to:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save()
.then(created_bucket => Promise.resolve(created_bucket))
.catch(next);
}
Up, running and ready for action!
When GET method is used, the below output comes but never completes loading... from POSTMAN Why?
Successfully connected to MongoDB instance!
MongoDB returned the following documents:
[ { _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Apple',
price: 2.5 },
{ _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Pear',
price: 3 },
{ _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Orange',
price: 3 } ]
When POST method is used, the below error occurred. Why?
/Users/json/Dev/restful_api/api.js:21
database.insert('OrderBase', resourceName, resource, function(err, resource) {
^
TypeError: database.insert is not a function
at insertResource (/Users/json/Dev/restful_api/api.js:21:12)
at insertProduct (/Users/json/Dev/restful_api/api.js:34:3)
at IncomingMessage.<anonymous> (/Users/json/Dev/restful_api/api.js:66:9)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Can anyone explain? I am new to NodeJs. Thanks a lot!
var http = require('http');
var database = require('./database');
var url = require('url');
// Generic find methods (GET)
function findAllResources(resourceName, req, res) {
database.find('OrderBase', resourceName, {}, function (err, resources) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resources));
});
};
var findResourceById = function (resourceName, id, req, res) {
database.find('OrderBase', resourceName, {'_id': id}, function(err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Generic insert/update methods (POST, PUT)
var insertResource = function (resourceName, resource, req, res) {
database.insert('OrderBase', resourceName, resource, function(err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Product methods
var findAllProducts = function (req, res) {
findAllResources('Products', req, res);
};
var findProductById = function (id, req, res) {
findResourceById('Products', id, req, res);
};
var insertProduct = function (product, req, res) {
insertResource('OrderBase', 'Product', product, function (err, result) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(result));
});
};
var server = http.createServer(function (req, res) {
// Break down the incoming URL into its components
var parsedURL = url.parse(req.url, true);
// Determine a response based on the URL
switch (parsedURL.pathname) {
case '/api/products':
if (req.method === 'GET') {
// Find and return the product with the given id
if (parsedURL.query.id) {
findProductById(id, req, res);
}
// There is no id specified, return all products
else {
findAllProducts(req, res);
}
}
else if (req.method === 'POST') {
//Extract the data stored in the POST body
var body = '';
req.on('data', function (dataChunk) {
body += dataChunk;
});
req.on('end', function () {
// Done pulling data from the POST body.
// Turn it into JSON and proceed to store it in the database.
var postJSON = JSON.parse(body);
insertProduct(postJSON, req, res);
});
}
break;
default:
res.end('You shall not pass!');
}
});
server.listen(8080);
console.log('Up, running and ready for action!');
database file
// Our primary interface for the MongoDB instance
var MongoClient = require('mongodb').MongoClient;
// Used in order to verify correct return values
var assert = require('assert');
/**
*
* #param databaseName - name of the database we are connecting to
* #param callBack - callback to execute when connection finishes
*/
var connect = function (databaseName, callback) {
// URL to the MongoDB instance we are connecting to
var url = 'mongodb://localhost:27017/' + databaseName;
// Connect to our MongoDB instance, retrieve the selected
// database, and execute a callback on it.
MongoClient.connect(url, function (error, database) {
// Make sure that no error was thrown
assert.equal(null, error);
console.log("Successfully connected to MongoDB instance!");
callback(database);
});
};
/**
* Executes the find() method of the target collection in the
* target database, optionally with a query.
* #param databaseName - name of the database
* #param collectionName - name of the collection
* #param query - optional query parameters for find()
*/
exports.find = function (databaseName, collectionName, query) {
connect(databaseName, function (database) {
// The collection we want to find documents from
var collection = database.collection(collectionName);
// Search the given collection in the given database for
// all documents which match the criteria, convert them to
// an array, and finally execute a callback on them.
collection.find(query).toArray(
// Callback method
function (err, documents) {
// Make sure nothing went wrong
assert.equal(err, null);
// Print all the documents that we found, if any
console.log("MongoDB returned the following documents:");
console.dir(documents);
// Close the database connection to free resources
database.close();
})
})
};
I'm writing a node app with React, using node-postgres and superagent for backend calls.
Let's say I'm making a GET request and using the JSON it returns to fill a table of students. My API looks like this:
import pg from 'pg';
import Router from 'express';
let router = new Router();
let conString = "postgres://user:pass#localhost/db_name";
router.get('/getStudents', function(req, res) {
var results = [];
pg.connect(conString, function(err, client, done) {
if (err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}
var query = client.query('SELECT first_name, last_name, email FROM students');
query.on('row', function(row) {
results.push(row);
});
query.on('end', function() {
done();
return res.json(results);
});
});
});
On page load, this is called from the store to set a students array. It seems like something is going wrong here:
var request = require('super agent');
function getStudents() {
request
.get('/api/getStudents')
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) {
console.log("There's been an error: getting students.");
console.log(err);
} else {
return res;
}
});
}
If I curl localhost:3000/api/getStudents, I get the JSON response I expect.
However, when I call this on page load, I get an ECONNREFUSED error:
Error: connect ECONNREFUSED 127.0.0.1:80]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 80,
response: undefined
Not sure why I'm getting an error on the HTTP port. This is my first time using node-postgres, superagent, and React so any help is appreciated.
Edit: Forgot to mention that I'm able to make POST requests and insert items into the database without any errors. This error only occurs when I'm attempting a GET request.
Try this (inserting the full path url) in the get method:
request
.get('http://localhost:3000/api/getStudents')
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) {
console.log("There's been an error: getting students.");
console.log(err);
} else {
return res;
}
});
Check out the documentation for CORS for an example of using absolute urls:
https://visionmedia.github.io/superagent/#cors
The error will also occur if you don't have the protocol in your request URL.
Instead
request.get('www.myexample.com/api/getStudents')
do
request.get('https://www.myexample.com/api/getStudents')
^^^^^^^^
// finding users
find: function (req, res, next) {
var userId = req.body.userId;
var userSchema = db.UserModel;
try {
db.sequelize.sync().then(function (params) {
userSchema.findAll({where:{userId:userId}}).then(function (user) {
return res.json({
success:true,
userData:user.get({
plain:true
})
});
});
});
} catch (ex) {
res.json({
success: false,
exception: ex
});
return;
}
}
I was writting simple crud api for my project.
while executing above mentioned code I am getting error on my console as:
Executing (default): SELECT userId, firstname, lastname, email, createdAt, updatedAt FROM Users AS User WHERE User.userId = '1';
Unhandled rejection TypeError: Cannot read property 'get' of undefined
at D:\tecsol\mtv\api\controllers\UserController.js:52:27
at processImmediate [as _immediateCallback] (timers.js:367:17)
user is an array - use findOne or user[0]