I am trying to learn node.js and I am stuck trying to send the JSON to the browser, I have not tried to consume the REST service because apparently the JSON is not being sent, it does not appear in postman.
This is my code:
Database connections pool
const mysql = require('mysql');
const pool = mysql.createPool({
host: "localhost",
database: "dbname",
user: "root",
password: "",
debug: true
});
module.exports.pool = pool;
Index
const Joi = require('joi');
const connections = require('./connections')
const express = require('express');
const app = express();
app.use(express.json());
function getClients() {
return new Promise((resolve, reject) => {
connections.pool.getConnection((error, connection) => {
connection.query("select * from clientes", (error, rows) => {
if(error) {
reject(new Error);
}
else {
resolve(JSON.stringify(rows));
}
})
connection.release();
})
});
}
app.get('/', (req, res) => {
getClients().then((rows) => {console.log(rows)})
.catch(err => err);
console.log(res);
res.end();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on port ${PORT}`));
In this part:
getClients().then((rows) => {console.log(rows)})
It logs the correct JSON response at the end however it calls a lot my attention that I am getting a very long server response before the JSON string.
when I use res.send(rows) it displays nothing, postman gives me 200 response and blank page.
I literally started learning NODEJS 3 days ago and I have been stuck with this for one day :(
You are not sending any data in response.
res.send does not send JSON it sends only string use res.json()
app.get('/', (req, res) => {
getClients()
.then((rows) => res.json(rows))
.catch(err => res.status(400).json(err));
});
Related
Hi I am trying to fetch data from server/index.js api endpoint data.getData() which is provided from api/data.js which in turn gets it's configuration and connection object from db/index.js. The problem is that the async/await is not returning anything and in the dev console network says pending. I don't receive any errors either. The code is below. Using node-pg with pool.query.
//server/index.js
const express = require("express");
const data = require("./api/data")
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json())
app.get('/', async (req, res) => {
// res.status(200).send('Hello World!');
await data.getData()
.then(response => {
res.status(200).send(console.log(response));
})
.catch(error => {
res.status(500).send(error);
})
console.log("server running")
})
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
//api/data.js
const db = require('../db/index.js');
const getData = async () => {
const query = {
// text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
text: 'SELECT Now()',
// values: ['B007RKDGVQ'],
// rowMode: 'array',
};
const dbResults = await db.query(query)
.then((data) => JSON.stringify(data))
.catch(error => {
console.log(error)
})
console.log("database response test")
return dbResults
}
// getData()
module.exports = {getData}
The setup is pretty simple but i can't understand why it is not working.
I am trying to connect to postgresql in digital ocean and all the connections and configs are correct. I have used the same setup similar but with electron.js and it works. I am able to retrieve the data easily.
Any help appreciated.
You should avoid using both async/await and then/catch at the same time. Use one of them.
server/index.js
const express = require("express");
const data = require("./api/data")
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json())
app.get('/', async (req, res) => {
// res.status(200).send('Hello World!');
try {
const result = await data.getData();
res.status(200).send(result);
} catch (error) {
res.status(500).send(error);
}
console.log("server running")
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
api/data.js
const db = require('../db/index.js');
const getData = async () => {
const query = {
// text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
text: 'SELECT Now()',
// values: ['B007RKDGVQ'],
// rowMode: 'array',
};
const dbResults = await db.query(query);
console.log("database response test", dbResults)
return JSON.stringify(dbResults)
}
module.exports = {getData}
Ok I have found the problem and it has nothing to do with the logic itself but more with the package I installed for PostgreSQL.
Instead of installing npm i pg I did instead npm i node-pg for some stupid reason.
After uninstalling and installing the correct package I am able to work with the PostgreSQL response.
I have been getting hanging requests, with only expressjs, on my windows 10 machine. The code I will post is the current version of the code; it was tried a) without async, and b) without redis anywhere and just the 'test' route. The request just hangs, whether called from Postman or accessed directly from a browser. Admin privileges were given with the same result.
const express = require('express')
import { createClient } from "redis"
import { UserApi } from "./api/users"
(async () => {
const app = express()
const client = createClient()
//Check redis
client.on('error', (err) => console.log('Redis Client Error', err))
//Connect to redis client
await client.connect()
//Create API instances
const ua = new UserApi(client)
//Initialize middleware\
app.use(express.json)
//Create routes
//test
app.get("/test", function(req, res) {
res.send("got")
})
//signup - creates user
app.post("/signup", async function(req, res) {
console.log("starting")
const u = {username: req.body.username, email: req.body.email, password: req.body.password}
console.log("why")
try {
console.log("trying")
const token = await ua.create(u)
res.send(token)
} catch (error) {
res.status(400).send(error)
}
})
app.listen(3000, () => {
console.log("server up")
})
}) ()
If I go to my site I get data from database. First Load is slow and takes 1-2 seconds. But then it is fast like 10ms. Why is the first connection slow? It is only when I use cassandra driver.
const http = require('http');
require('dotenv').config();
const { Client } = require('cassandra-driver');
const express = require('express');
const app = express();
const PORT = process.env.PORT;
const routes = require('./src/routes/index');
const client = new Client({
cloud: {
secureConnectBundle: "secure-connect-weinf.zip",
},
keyspace: 'wf_db',
credentials: {
username: "username",
password: "password",
},
});
const cors = require('cors');
app.use(cors());
app.use(express.json());
app.get('/', async (req, res) => {
await client.connect();
const rs = await client.execute("SELECT * FROM employ_by_id;");
console.log(rs);
return res.json({
message: 'Hello'
})
});
const server = http.createServer(app);
server.listen(PORT, () => {
console.log(`Server listen on port ${PORT}`)
});
Your code is connecting (creating the TCP connections) the first time:
app.get('/', async (req, res) => {
await client.connect(); // <- this should be avoiding in the serve path
const rs = await client.execute("SELECT * FROM employ_by_id;");
console.log(rs);
return res.json({
message: 'Hello'
})
});
To mitigate this, you can create the connections beforehard:
app.get('/', async (req, res) => {
const rs = await client.execute("SELECT * FROM employ_by_id;");
console.log(rs);
return res.json({
message: 'Hello'
})
});
const server = http.createServer(app);
client.connect(err => {
//TODO: Handle err
// ...
// Now that I'm connected to my DB, I can start serving requests
server.listen(PORT, () => {
console.log(`Server listen on port ${PORT}`)
});
});
Reads from disk are always slower than reads from memory. When you query for the first time, Cassandra database reads from the disk which gets you a slow result. Second time Cassandra replies from the cached rows if caching is enabled, hence you get your results faster.
PS : Please dont execute "select * from table" queries, they are kind of anti pattern in Cassandra.
I am building an API that uses socket connection to interact with a server backend built in C#. This is what I have so far
const request = require('request');
const express = require('express');
const app = express();
var server = require('http').createServer(app);
var cors = require("cors");
app.use(cors());
const net = require('net');
const client = new net.Socket();
const stringToJson=require('./stringToJson')
const port = process.env.PORT;
const host = process.env.HOST;
client.keepAlive=true
client.on('close', function() {
console.log('Connection closed');
});
app.get('/getScores',function (req,res) {
let dataSend=''
client.on('data', function (data) {
console.log('Server Says : ' + data);
if(data!='ANALYSIS-ERROR'){
dataSend=stringToJson.stringToJson(data)
}
else{
dataSend=stringToJson.stringToJson('0:0.0:0.0:0.0:0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0')
}
client.destroy()
return res.send(dataSend)
});
client.connect(port, host, function () {
client.write(`GENERAL-ANALYSIS|${req.query.id}|${req.query.website}|`)
return
});
return
})
app.get('/getPlace',function (req,res) {
console.log(req.query)
request(
{ url: `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${req.query.name}+in+${req.query.city}&key=${process.env.API_KEY}` },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: error.message });
}
return res.json(JSON.parse(body));
}
)
})
//TODO ADD 404 500 PAGES
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
server.listen(9000, () => {
console.log(`App running at http://localhost:9000`);
});
Basically it creates a connection with the server and listens for some data to be sent back. Then processes the string and sends it to the React frontend. The api calls are made by the frontend using axios
It works but if you refresh the page it throws this error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How do I fix this?
Try setting the headers as found in the documentation request.setHeader(name, value)
request.setHeader('Content-Type', 'application/json');
OK, so I am successfully running expressjs on windows iis server localhost:5000 and getting the expected json response using the following code...
server.js
const express = require('express');
var cors = require('cors')
const api_helper = require('./API_helper')
//const api_helper = require('./api')
const app = express();
const port = process.env.PORT || 5000;
require('ssl-root-cas/latest')
.inject()
.addFile('./root.crt')
.addFile('./****.crt')
// create a GET route
/* app.get('/express_backend', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
}); */
app.get('/express_backend', (req, res) => {
res.type('json')
api_helper.make_API_call('https://*my_api_server*/api/company/')
//api_helper.make_API_call('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
res.send(response)
})
.catch(error => {
res.send(error)
})
})
app.listen(port, () => console.log(`App listening on port ${port}!`))
API_helper.js
const request = require('request')
module.exports = {
/*
** This method returns a promise
** which gets resolved or rejected based
** on the result from the API
*/
make_API_call : function(url){
return new Promise((resolve, reject) => {
res.set('Content-Type', 'application/json');
request(url, { json: true }, (err, res, body) => {
if (err) reject(err)
resolve(body)
});
})
}
}
Screenshot of successful response using localhost:5000...
My question is, how would I get this to work using a domain name instead of localhost? When I use our https domain name, I get no response headers and just the raw html for server.js
Thanks.
When running on a port less than 1025, you need to run the server with escalated privileges.
If running on Windows ensure that your Command Line is running with Administrator Permissions.
With Linux:
sudo node server.js