So I have built my server like this:
var mysql = require('mysql2');
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
var PORT = 2096;
app.get('/getDataFromDatabase', function(req, res) {
console.log("Called")
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "casesdb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM totalValues", function (err, result, fields) {
if (err) throw err;
res.status(200).send(result);
console.log("Test")
});
});
});
app.listen(PORT, () =>
console.log(`Example app listening on port ${PORT}!`),
);
and I'm calling it like this:
$( document ).ready(function() {
$.get('http://localhost:2096/getDataFromDatabase').done(function(data){
for (entry of data) {
dates.push(entry.date.split('T')[0]);
totalValues.push(entry.totalValue);
}
});
});
I have tested all of this on my local PC and it works just fine. I now uploaded it to my Ubuntu Server. Something I might want to add is that I'm using cloudflare and a domain to access the website of course. All request get refused like this (print in console):
GET http://localhost:2096/getDataFromDatabase net::ERR_CONNECTION_REFUSED
Any help is appreciated.
I believe it's because you are trying to access localhost but your express server isn't running on your local machine, it's on your domain.
Try:
http://<yourDomainHere>:3000/getDataFromDatabase
Also, your domain might be refusing any http requests by default.
Related
I'm probably doing something silly, and putting myself in a situation that I don't need to be in. But my ultimate question is why do I have to have an empty folder in my server in order for my GET requests to work?
Before I start with an example, everything is under a subfolder: http://www.example.org/subfolder1
Here is Server code:
const express = require('express');
const datastore = require('nedb');
const url = require("url");
var path = require('path');
const app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server,
{
path: '/subfolder1/socket.io',
cors:
{
origin: '*',
methods: ["GET", "POST"],
credentials: true
}
});
const port = 3000;
io.on('connection', socket => {
console.log("Socket connected: " + socket.id);
});
app.get("/subfolder1/getSettings", (req, res, next) => {
res.json({ configuration: conf });
});
app.use(express.json());
app.get("/subfolder1/", function (req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.use(express.static(path.join(__dirname, 'public')));
server.listen(port, '0.0.0.0', function(error){
if(error) {
console.log('Server failed to listen: ', error)
} else{
console.log('Server is listening on port: ' + port)
}
});
client code:
const response = await fetch("/subfolder1/getSettings");
const settings = await response.json();
Now, in this example I'm calling getSettings (http://www.example.org/subfolder1/getSettings):
app.get("/subfolder1/getSettings", (req, res, next) => {
res.json({ configuration: conf });
});
No matter what I do, I will forever get a 404 error message unless I create an empty folder called "getSettings" in my folder structure on my server. Once I create the empty folder, the call works! So for now, I've just making empty folders on my server for my get calls. Well now look what happens when the URL is something more complicated, such as the following:
http://www.example.org/subfolder1/team=6/queuedPlayers (Where team can be any integer)
Now I'm stuck and my workaround is broken. Any ideas?
I am trying to pass some coordinates from mysql database to be marked on a map but am having trouble getting them. i have looked at a number of similar questions on stackoverflow and have not been able to find an answer. Would appreciate if someone could please point out where i have gone wrong.
getListings.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config);
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
connection.query('SELECT listing_coords FROM listings', (err, rows) => {
if (err) throw err;
console.log('Data received from Db:\n');
var results = JSON.parse(JSON.stringify(rows));
module.exports = { results };
console.log(results);
});
});
Then in my script.js file i have
var { results } = require('./getListings');
console.log(results);
I am getting an error in the browser console saying "require is not defined"
I will need to figure out how to pull the coordinates from mysql in order to plot them, there has to be a way? Do i have to build an api and use ajax? Thanks in advance for any help.
have updated my getListings.js file - it now displays in the string of data i need in the browser as a raw data packet
var mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
app.listen(5000, () => console.log('express server is running at 5000'));
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
I have been unsuccessful to get the output to run in script.js. I will post the working code when its working.
I am getting an error in the browser console saying "require is not defined"
It is because require is not an API for frontend. It should be the syntax of backend(eg. nodeJS).
Do i have to build an api and use ajax?
If you wanna to send data from frontend to backend. Using ajax is possible but the main point is you need to have a backend server(eg. using Express module for nodeJS) to connect with the database(eg. mysql, postgresSQL).
Update on 14 Feb, 2021
My practise for doing this is to use ajax to send a request to the backend server from frontend.
//frontend
$.ajax
({
url: "yourBackendServerUrl", //eg. localhost:8001/listing. Need modification based on your backend setting.
})
.done(function(data) {
console.log(data) //data should be the result from backend, then you can retrieve the data for frontend usage
});
For the CORS problem, you can install cors package. If you have a middleware in the global scope(a.k.a. app.use(cors()) ). Every time there are request, this middleware will run.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors()) // pay attention to this line of code.
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
The solution that I got to work is as follows:
getListings.js (this was nodeJS)
var mysql = require('mysql');
const express = require('express');
const bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
**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, Authorization'
);
next();
});**// I believe this is a middleware function
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
app.listen(5000, () => console.log('express server is running at 5000'));// this can be any port that isnt currently in use
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
in my script.js file i was missing the following
$.get('http://localhost:5000/listings', function (data, status) {
console.log('Cords Data', data);
I believe that is the jQuery ajax
Then in the heading of my html I needed the following
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type = "module" defer src="script.js"></script>
thanks to everyone that helped me with this. especially #tsecheukfung01.
I dont fully understand all of the pieces so it will take me a while to fully understand this and be able to recreate this on my own. All part of the journey!
I've been trying to create an app that uses telegram-bot, express server and react app. Therefore, I need to create a POST request from telegram-bot to express, while express sends POST data to a websocket connection:
const express = require("express");
const app = express();
const expressWs = require("express-ws")(app);
// handles bot request
app.post("/request", (req, res) => {
playlist.push(req.body.url);
res.status(200).send({ message: "video is added to playlist" });
});
// after handling requst data must go here and send ws message to client side
app.ws("/echo", (ws, req) => {
ws.on("message", msg => {
ws.send(`msg is = ${msg}`);
});
});
Am I making it right, and if so, how to call ws.send from after handling request at app.post route?
From the understanding I have from your question, here is an updated version of your code that does exactly what you want.
I replaced the express-ws package with ws since that would be sufficient for your use case.
The express server runs on port 8080 while the websocket server runs on port 8081 since are different protocols and would not run on the same port (You can make it work but I do not recommend it See this question
const express = require("express");
const Websocket = require('ws');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const wss = new Websocket.Server({ port: 8081 });
wss.on('connection', (ws) => {
console.log('One client connected');
ws.on("message", msg => {
ws.send(`msg is = ${msg}`);
});
})
// handles bot request
app.post("/request", (req, res) => {
// Broadcast URL to connected ws clients
wss.clients.forEach((client) => {
// Check that connect are open and still alive to avoid socket error
if (client.readyState === Websocket.OPEN) {
client.send(url);
}
});
res.status(200).send({ message: "video is added to playlist" });
});
app.listen(8080, () => {
console.log('Express listening on 8080');
console.log('Websocket on 8081');
});
Tested via curl with curl -d 'url=https://example.com/examplesong' localhost:8080/request I had a client connected to ws://localhost:8081 and everything looks good.
I am creating a simple web application using node.js, express and mysql.
When I connect to get /employees, I try to console.log the data of the linked DB. However, when connected to localhost, an infinite delay occurs.
What's wrong with me?
index.js
const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json)
var mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'ps',
database: 'EmployeeDB'
});
mysqlConnection.connect((err) => {
if(!err)
console.log('DB connection succeded');
else
console.log('DB connection failed \n Error : '+ JSON.stringify(err, undefined, 2));
});
app.listen(3000, () => console.log('Express server is running at port no:3000'));
app.get('/employees',(res, req)=> {
mysqlConnection.query('SELECT * FROM Employee',(err, rows, fields)=>{
if(!err)
console.log(rows);
// console.log(rows[0].EmpID);
else
console.log(err);
})
});
You need to return something, like the data:
app.get('/employees',(req, res)=> {
mysqlConnection.query('SELECT * FROM Employee',(err, rows, fields)=>{
if(!err)
res.json(rows);
else
res.status(500).send('Error found');
})
});
Also, parameters are reversed from normal – (res, req) vs. (req, res) as #JonathanLonowski catch it.
I am building a proxy server which is supposed to forward data from an Shoutcast server to the client. Using request or even Node's http module this fails due to missing HTTP header:
{ [Error: Parse Error] bytesParsed: 0, code: 'HPE_INVALID_CONSTANT' }
The URL in question is: http://stream6.jungletrain.net:8000
Doing a header request with curl I was able to verify this:
$ curl -I http://stream6.jungletrain.net:8000
curl: (52) Empty reply from server
Yet the stream is working fine as tested with curl stream6.jungletrain.net:8000.
Is there a way to disable the header verification in request or Node's http? This is the code I am testing it on:
var express = require('express');
var request = require('request');
var app = express();
app.get('/', function (req, res) {
request('http://stream6.jungletrain.net:8000').pipe(res);
stream.pipe(res);
});
var server = app.listen(3000, function () {
console.log('Server started')
});
I am aware this can be achieved by rolling an implementation with net, there is also icecast-stack but subjectively seen it only implements half of the Stream interfaces properly.
Using icecast, I was able to get this working both using the on('data') event and by piping it to the Express response:
var express = require('express');
var app = express();
var icecast = require('icecast');
var url = 'http://stream6.jungletrain.net:8000';
app.get('/', function(req, res) {
icecast.get(url, function(icecastRes) {
console.error(icecastRes.headers);
icecastRes.on('metadata', function(metadata) {
var parsed = icecast.parse(metadata);
console.error(parsed);
});
icecastRes.on('data', function(chunk) {
console.log(chunk);
})
});
});
var server = app.listen(3000, function() {
console.log('Server started')
});
Or simply:
app.get('/', function(req, res) {
icecast.get(url).pipe(res);
});
Also of some note:
It appears the icecast package has been superseded by https://www.npmjs.com/package/icy