reponse is empty in client side in nodejs - node.js

I am able to see the response in post man but when i checked in network with client side i am getting 200 ok but i am not getting any response.I think it may be because of CORS.Can some one suggest me help.
my js,
I am sending users/1 from my client side but i am not even getting the param1 to my function in backend
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var app = express();
var cors = require('cors')
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var connection = mysql.createConnection({
// connectionLimit : 100, //important
host : 'localhost',
user : 'root',
password : 'root',
database : 'socialwiki'
});
connection.connect(function(error){
if(!!error){
console.log('error');
}else{
console.log('connected');
}
});
exports.getlist = function( req, res ) {
console.log(req.id);
connection.query("SELECT * FROM profile",function(error,result,rows,fields){
if(!!error){
console.log('fail');
}else{
console.log(result);
res.send(result);
}
// }
});}

If CORS in the problem you could use the node module cors
Here is a example on how to configure cors with express!

replace the above code with below to allow cross-request the
var express = require('express');
var mysql = require('mysql');
var app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json({ limit: '50mb' }));
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'access-control-allow-methods,access-control-allow-origin,x-access-token,content-type,Origin, X-Requested-With, Accept');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
var connection = mysql.createConnection({
// connectionLimit : 100, //important
host : 'localhost',
user : 'root',
password : 'root',
database : 'socialwiki'
});
connection.connect(function(error){
if(!!error){
console.log('error');
}else{
console.log('connected');
}
});
exports.getlist = function( req, res ) {
console.log(req.id);
connection.query("SELECT * FROM profile",function(error,result,rows,fields){
if(!!error){
console.log('fail');
}else{
console.log(result);
res.send(result);
}
});
};

Related

Angular route is not working in Combined MEAN?

I created a single page app using Angular.I'm using Node/Express on the back-end. While Express is serving my static index.html correctly.
When i try to navigation to some angular route from url address bar it saying cannot get /login...
i found this question on stackoverflow it is exactly what i am saying but its not answered yet.
Angular - Routing is not working (MEAN)
Here is my code.
var path = require("path");
var express = require("express");
var mongoose = require("mongoose");
var app = express();
require('./startups/prod')(app);
// Temp.
const TempRoutes = require("./routes/temp");
mongoose.connect('mongodb://localhost:27017/node-angular', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("Connected to database.");
})
.catch(() => {
console.log("Connection Failed.");
});
app.use(express.json());
app.use("/", express.static(path.join(__dirname, "dist")));
app.use((request, response, next) => {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requesed-With, Content-Type, Accept,Accept-Language,Content-Language, Authorization");
response.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS");
next();
});
app.use((request, response, next) => {
response.sendFile(__dirname, path.join("dist", "index.html"))
})
module.exports = app;

incomplete response received from application nodejs

I'm using nodejs on nginx server. Sometimes the node app is crashing and returning 'incomplete response received from application'. What is causing this problem?
const Express = require('express');
const BodyParser = require('body-parser');
const Request = require('request');
const Conf = require('./conf');
const {db} = require('./lib/database');
const app = Express();
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'POST');
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Methods', 'POST');
return res.sendStatus(200);
}
next();
});
app.post('/getProperty', (req, res) => {
const sql = "SELECT ('['||(st_asgeojson(geom)::json)||']')::json FROM spt.spt where id=" + req.body.id;
db.query(sql, (err, result) => {
if (err) res.status(err.code).json({code: err.code, message: err.message}).end();
(result.rows.length == 0) ? res.send([]) : res.send(result.rows[0].json);
})
});
app.post('/getAnalysis', (req, res) => {
const sql = "select value from test.test where id=" + req.body.id + " order by value asc";
db.query(sql, (err, result) => {
if (err) result.status(err.code).json({code: err.code, message: err.message}).end();
res.send(result.rows);
})
});
app.listen(3000);
If an error occurs, your code tries sending a response twice. You need to exit the function after sending the error response to the client, so either use return in your if or add an else below for the success response.
Sending multiple responses will dicsonnect the socket in express.

NodeJS : Passport JWT(v4.0.0) failed to authenticate user from POSTMAN Rest Client , Always return Unauthorized

I am using express js as backend framework, currently working on login authentication module using Passport-JWT,
I want to use authentication middleware on private routes .
I don't want to write passport.authenticate('jwt', {session: false} on every route , instead i want to make one function and use it on every request like
router.get('/current',isAuthenticated,controllers.auth.user);
login authentication working properly , but after that when I access private route , it always gives "Unauthorized."
I have searched so many same question but any of not working for me , so I ask this question again
when user suceessfull login , following token has been stored in localstorage.
When I tried from Postman rest client
it gives unauthorized when i use passport.authenticate('jwt', {session: false}
it show error {name: 'JsonWebTokenError', message: 'invalid signature' } passport middleware when i use isAuthenticate
I am using this package version :
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"jsonwebtoken": "^8.3.0",
Here is my helpers/passport.js
const options = {};
options.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
options.secretOrKey = 'qwer123poiuasdf234092482094';
module.exports = passport => {
passport.use(
new JwtStrategy(options, (jwt_payload, done) => {
User.findById(jwt_payload._id)
.then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => {
console.log(err);
return done(err, false);
});
})
);
};
Here is my server.js
global.express = require('express');
global.app = express();
global.passport = require('passport');
global.jwt = require('jsonwebtoken');
global.JwtStrategy = require('passport-jwt').Strategy;
global.ExtractJwt = require('passport-jwt').ExtractJwt;
global.logger = require('morgan');
global.Validator = require('validator');
global.bcrypt = require('bcrypt-nodejs');
global.crypto = require('crypto');
global.bodyParser = require('body-parser');
global.cookieParser = require('cookie-parser');
global.requireTree = require('require-tree');
global.mongoose = require('mongoose');
global.autoIncrement=require('mongoose-auto-increment');
mongoose.Promise = Promise;
mongoose.set('useCreateIndex', true);
var mongooseOptions = { useNewUrlParser: true }
global.Schema = mongoose.Schema;
autoIncrement.initialize(mongoose);
global.rootdir = __dirname;
global.ejs=require('ejs');
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
global.configuration = requireTree(rootdir + '/configuration')
global.helpers = requireTree(rootdir + '/helpers')
require(rootdir+'/helpers/passport')(passport)
global.validation = requireTree(rootdir + '/validation')
mongoose.connect(configuration.config.MONGODB_URI, mongooseOptions, function(err) {
if (err) {
console.error('System could not connect to mongo server.')
console.log(err)
process.exit()
} else {
console.log('System connected to mongo server.')
}
});
app.use(logger('dev'));
app.use(passport.initialize())
app.use(express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 100000
}))
app.use(bodyParser.json({
limit: '50mb',
parameterLimit: 100000
}))
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Request-Headers", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
// this function i want to use as middleware on private routes
global.isAuthenticated=function(req, res, next) {
if (req.headers.authorization) {
passport.authenticate('jwt', {session: false}, function (err, user, info) {
console.log('errr==',err);
console.log('user==',user);
console.log('info==',info);
if ((!err || !info) && user) {
req.user = user;
return next();
}
res.status(401).json({status:'error',isAuthenticated: false, message: "Unauthorized"});
})(req, res, next);
} else {
res.status(401).json({status:'error',isAuthenticated: false, message: "Unauthorized"});
}
}
app.use('/api/auth',routes.api.auth);
var port = process.env.PORT || 8888;
app.listen(port);
here is routes/api/auth.js
const router=express.Router();
router.get('/current',isAuthenticated,(req,res)=>{
res.json({
user:req.user
});
});
module.exports =router
please help me to solve this issue
First of all, the 'Could not get any response' error is not due to the authentication error, it might be because server is down or API route is not there.
Second, make sure you are using you have configured token to have Bearer otherwise send only token(without Bearer).
I think in your case, you are not sending correct token(try removing
Bearer) from client.

How do I pass a const to my scope

I m trying to use the node-binance-api to retreive cryptocurency value.
I am able to get the information and display it in the node console.
Im doing so like this;
var express = require('express');
var app = express();
var mongo = require('mongodb');
var db = require('mongojs')("mongodb://URL")
var nodeBinanceApi = require("node-binance-api");
const binance = require('node-binance-api')().options({
APIKEY: '***',
APISECRET: '***',
useServerTime: true, // If you get timestamp errors, synchronize to server time at startup
test: true // If you want to use sandbox mode where orders are simulated
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
binance.prices((error, ticker) => {
console.log("Price: ", ticker); <--------------------------
console.log("Price of BTC: ", ticker.BTCUSDT);
});
app.use(express.static(__dirname + '/www'));
app.listen(81);
I would like to pass the json information in ticker to my scope in another script on the page. Should i use routes? and the use get request in the scope?
It does work with routes!
I added
app.get('/crypto', function(req, res){
//calling the function
binance.prices((error, ticker) => {
res.jsonp(ticker);
console.log(ticker);
});
return;
});
Now I can see the prices of all cryptosurrency on my page!

Invalid status code : 0 in node.js API

I am building a simple api in node and express with postgre as Db following a tutorial.I am still learning and new to this tech.I followed everything as said and gave full permission to postgre thinking about issue with my db.But when i check it with postman i am getting this error Invalid Status Code : 0
my server.js
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var api = require('./api/index');
var app = express();
///////////////////////
// Server Middleware
///////////////////////
app.use(logger(app.get("env") === "production" ? "combined" : "dev"));
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// CORS
// This allows client applications from other domains use the API Server
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//////////////////
// API Queries
//////////////////
app.use('/', api);
//////////////////
// Server Setup
//////////////////
app.set("env", process.env.NODE_ENV || "development");
app.set("host", process.env.HOST || "0.0.0.0");
app.set("port", process.env.PORT || 8080);
app.listen(app.get("port"), function () {
console.log('\n' + '**********************************');
console.log('REST API listening on port ' + app.get("port"));
console.log('**********************************' + '\n');
});
////////////////////
// Error Handlers
////////////////////
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status( err.code || 500 )
.json({
status: 'error',
message: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500)
.json({
status: 'error',
message: err.message
});
});
module.exports = app;
queries.js
var promise = require('bluebird');
var options ={
promiseLib : promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/star';
console.log(connectionString);
var db = pgp(connectionString);
function getAllStarships(req, res, next) {
db.any('SELECT * FROM starships')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved all starships'
});
})
.catch(function (err) {
return next(err);
});
}
module.exports ={getAllStarships: getAllStarships,};
index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.status(200)
.json({
status: 'success',
message: 'Live long and prosper!'
});
});
var db = require('./queries');
router.get('/api/starships', db.getAllStarships);
module.exports = router;
Querying Db is working fine from the pgadmin editor and returning the table.
Sample DB
DROP DATABASE IF EXISTS startrek;
CREATE DATABASE startrek;
\c startrek;
CREATE TABLE starships (
ID SERIAL PRIMARY KEY,
name VARCHAR,
registry VARCHAR,
affiliation VARCHAR,
launched INTEGER,
class VARCHAR,
captain VARCHAR
);
INSERT INTO starships (name, registry, affiliation, launched, class, captain)
VALUES ('USS Enterprise', 'NCC-1701', 'United Federation of Planets Starfleet', 2258, 'Constitution', 'James T. Kirk');
Any Help Appreciated.
Thanks.
Got this..Problem was with Authentication.Modified my query.js with
var db = pgp({
host: 'localhost',
port: 5432,
database: 'star',
user: 'postgres',
password: 'pes'
});
And it worked.

Resources