Module not found: Can't resolve 'fs' in '.../node_modules/destroy' using Next.js mysql Express React - mysql

I would like to insert data from pages/index.js into mysql database.
A mysql connection in routes/routes.js, i have built ins function to call what i want
Structure
components
pages
index.js
routes
routes.js
server.js
package.json
Fail with error:
Module not found: Can't resolve 'fs' in '.../node_modules/destroy'
pages/index.js
import React, { Component } from "react";
import { Typography, Button, Grid } from "#material-ui/core";
import QRCode from "qrcode.react";
import dynamic from "next/dynamic";
import { PublicKey, SecretKey, HOSPCODE } from "../stellar";
const { ins } = require("../routes/routes"); //This is the problem!
const StellarSdk = require("stellar-sdk");
const QrReader = dynamic(() => import("react-qr-reader"), {
ssr: false
});
export default class QR extends Component {
state = {
result: "",
camera: true,
msg: "",
QR: {}
};
_clear = () => {
this.setState({ result: "", camera: true, msg: "", QR: {} });
};
handleScan = data => {
if (data) {
const dataJson = JSON.parse(data);
if (dataJson.Type == "Patient") {
const KP = StellarSdk.Keypair.fromSecret(SecretKey);
this.setState({
result: dataJson,
QR: JSON.stringify({
Type: "Hospital",
HospitalName: "xxx Hospital",
EndPoint: "xxx/patientID_",
SPK: PublicKey,
Signature: KP.sign(
Buffer.from(dataJson.ID + dataJson.SPK)
).toString("base64")
}),
camera: false,
msg: ""
});
ins(dataJson.ID, HOSPCODE, dataJson.SPK, dataJson.SecretKey);
} else {
this.setState({
msg: "Wrong QRCode."
});
}
}
};
But /routes/routes in server.js work.
const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const bodyParser = require("body-parser");
const { router, ins } = require("./routes/routes");
app
.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use("/api", router);
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(3001, err => {
if (err) throw err;
console.log("> Ready on http://localhost:3001");
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});
routes/routes.js
const express = require("express");
const mysql = require("mysql");
const router = express.Router();
const dotenv = require("dotenv").config();
const connection = mysql.createConnection({
host: process.env.DATABASE_HOST,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
port: 3306
});
console.log("Connecting...");
connection.connect(function(err) {
if (err) return new Error("An error occured during SQL connection " + err);
console.log("Connected!");
});
console.log(connection.config);
/* GET home page. */
router.get("/", function(req, res, next) {
...
...
...
ins = (cid, HOSPCODE, spk, secretKey) => (cid, HOSPCODE, spk, secretKey) => {
var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
var values = [[cid, HOSPCODE, spk, secretkey]];
connection.query(sql, [values], function(err, result) {
if (err) throw err;
});
};
module.exports = { router, ins };
I am new at Next.js and React. There is a better way to insert data from pages/index.js into mysql database? Please let me know.
"dependencies": {
"#material-ui/core": "^4.9.0",
"#material-ui/icons": "^4.5.1",
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"fs": "^0.0.1-security",
"mysql": "^2.18.1",
"next": "^9.2.1",
"qrcode.react": "^1.0.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-qr-reader": "^2.2.1",
"stellar-sdk": "^3.3.0",
"typeface-roboto": "^0.0.75"
}
Ubuntu 18.04 x64,
mysql Ver 14.14 Distrib 5.7.28,
Node v12.14.1

At last, i have to post request to my server via the same server on frontend(index.js) to insert data into mysql database.
I'm not sure. because of SSR(Next.js), i cannot send data back to backend.
But
I still need other method except post request into itself.
routes/routes.js
router.post("/secret/", cors(corsOptions), function(req, res, next) {
var sql = "INSERT INTO STELLARKEY (CID, HOSPCODE, SPK, SecretKey) VALUES ?";
var values = [
[req.body.cid, req.body.HOSPCODE, req.body.spk, req.body.secretkey]
];
connection.query(sql, [values], function(err, result) {
if (err) console.log(err);
});
});
module.exports = router;
pages/index.js
fetch("http://localhost:3001/api/secret", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
cid: dataJson.ID,
HOSPCODE: HOSPCODE,
spk: dataJson.SPK,
secretkey: dataJson.SecretKey
})
});
server.js
const router = require("./routes/routes");
app
.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use("/api", router);
server.get("*", (req, res) => {
return handle(req, res);
});

As long as we don't run next build and don't start app with NODE_ENV=production, this issue won't happen.
We use NODE_ENV=dev to circumvent this issue for the moment. I mean we use npm run dev to deploy now. This can only be considered a temporary solution.
"scripts": {
"dev": "NODE_ENV=dev node server.js",
"start": "node server.js",
"deploy": "next build && NODE_ENV=production node server.js"
}

Related

In node.js, How to return mysql results from a function?

I tried to separate function to another file, as the function fetching data from mysql database.
This is db.js
const mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "sample"
});
con.connect()
module.exports = function(query) {
con.query(query, function (err, result) {
if (err){
console.log(err);
} else{
console.log(result)
return result
}
});
};
This is main.js
const express = require('express')
const db = require('./db')
const app = express()
app.get('/test', function(req, res){
var sql = "SELECT id FROM user"
console.log(db(sql))
res.send(db(sql))
});
In main.js on console.log(db(sql)) got undefined.
But in db.js on console.log(result) I got the values as:
[
RowDataPacket { id: 1 },
RowDataPacket { id: 2 },
RowDataPacket { id: 3 }
]
Why did I get undefined in the main.js? Is there any solution for this issue?
Since you are using callback function, you can't directly return the value from it.
you have 2 options to do what you want to do.
Promise
Async/Await (mysql2 module needed)
Try this,
Querying
function(query) {
return new Promise((resolve, reject) =>{
try{
con.query(query, function (err, result) {
if (err){
return reject(err)
}
return resolve(result)
});
}
catch(e){
reject(e)
}
})
};
Main
app.get('/test', async function(req, res){
var sql = "SELECT id FROM user"
try{
const userId = await db(sql)
return res.send({
success: true,
result: {
userId
}
})
}
catch(e){
console.error(e)
return res.status(500).send({
success: false,
message: 'internal server error'
})
}
})
One more thing, if you have a good reason to write query by yourself, you can use
knex for making it easier (https://www.npmjs.com/package/knex), which is a query builder, meaning doing nothing to do with database connection.
Sollution
Try async/await with mysql2
Dont go for mysql2/primse because it will cause unexpected errors when your database is in the cloud or deployed somewhere like clearDB addons provided by Heroku
Follow these steps...
create config file for your database connection seperately
import mysql from 'mysql2'
let db = mysql.createPool({
host: 'your host name',
user: "your username",
password: "your password",
database: "your database name",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
export { db }
execute the query the same like this i am doing
import {db} from 'where you defined the above db config'
app.get('/test', async function(req, res){
const promise= db.promise()
var sql = "SELECT id FROM user"
const [rows,field] = awiat promise.execute(sql)
res.send(rows)
});

express js - GET request 404 not found when using sequelize

I am using Sequelize and express.js in server development.
When I try to send GET request for route /files, an error shows:
{
"errors": {
"message": "Not Found",
"error": {
"status": 404
}
}
}
Folder structure
src
-models
-File.js
-routes
-api
-index.js
-files.js
-index.js
-app.js
-sequelize.js
package.json
I am trying to get ALL records from table files
/src/routes/api/files.js
const router = require('express').Router();
const Files = require('../../models/File')
router.get('/files', (req,res) =>
Files.findAll()
.then(data => {
res.sendStatus(200)
})
.catch(err => console.log(err))
);
module.exports = router;
/src/routes/index.js
var router = require('express').Router();
router.use('/api', require('./api'));
module.exports = router;
/src/models/File.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
const db = require('../sequelize')
let files = db.define('files', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
fileName: {
type: DataTypes.STRING
},
});
module.exports = files;
src/sequelize.js
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('myDb', 'admin', '1234', {
dialect: 'mysql',
logging: false
});
sequelize.sync({alter: true})
module.exports = sequelize;
src/app.js
var http = require('http'),
path = require('path'),
methods = require('methods'),
express = require('express'),
bodyParser = require('body-parser'),
session = require('express-session'),
cors = require('cors'),
passport = require('passport'),
errorhandler = require('errorhandler'),
mongoose = require('mongoose');
const sequelize = require('./sequelize')
sequelize.authenticate()
.then(() => {console.log("connected")}) //printed "connected"
.catch((err) => {console.log(err)})
var isProduction = process.env.NODE_ENV === 'production';
var app = express();
app.use(cors());
app.use(require('morgan')('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('method-override')());
app.use(express.static(__dirname + '/public'));
app.use(session({ secret: 'conduit', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }));
if (!isProduction) {
app.use(errorhandler());
}
if(isProduction){
mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.connect('mongodb://localhost/conduit');
mongoose.set('debug', true);
}
require('./models/File');
app.use(require('./routes'));
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if (!isProduction) {
app.use(function(err, req, res, next) {
console.log(err.stack);
res.status(err.status || 500);
res.json({'errors': {
message: err.message,
error: err
}});
});
}
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({'errors': {
message: err.message,
error: {}
}});
});
var server = app.listen( process.env.PORT || 3000, function(){
console.log('Listening on port ' + server.address().port);
});
Update 1
src/routes/api/index.js
var router = require('express').Router();
router.use('/', require('./users'));
router.use('/files', require('./files'));
router.use(function(err, req, res, next){
if(err.name === 'ValidationError'){
return res.status(422).json({
errors: Object.keys(err.errors).reduce(function(errors, key){
errors[key] = err.errors[key].message;
return errors;
}, {})
});
}
return next(err);
});
module.exports = router;
Edit
In your /api/index.js file you have :
router.use('/files', require('./files'));
So the URL should be: http://localhost:3000/api/files/files
If you want to change the URL to: http://localhost:3000/api/files, in your files.js, you should change to :
router.get('/', (req,res) => // change "/files" to just "/"
Files.findAll()
.then(data => {
res.sendStatus(200)
})
.catch(err => console.log(err))
);

React-Native JSON Parse error: Unexpected identifier "var"

Im trying to make a login screen for my react-native app, but when I try to login I get the error message 'JSON Parse error: unexpected token "var" ' displayed.
I have a react native app and a server app in a different folder which I acces via localhost.
I have tried to change var to let to see what would happen, but then I would get the same error, but with let instead.
This is my react-native code
login = () => {
fetch('http://192.168.0.105:8888/loginbackend/routes/users.js', {
method: 'POST',
header: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
})
.then((response) => response.json())
.then ((res) => {
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('Profile');
}
else {
alert(res.message);
}
})
.done();
}
}
My server file
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'users'
});
router.POST('/', function(req, res) {
var username = req.body.username;
var password = req.body.password;
connection.query(
"SELECT * FROM user WHERE username = ? AND password = ?",
[username, password], function (err, row){
if (err) {
console.log(err);
res.send({ 'success': false, 'message': 'Kan niet met de database verbinden'});
}
if (row.length > 0 ){
res.send({ 'success': true, 'user': row[0].username });
} else {
res.send({ 'success': false, 'message': 'Gebruiker niet gevonden'});
}
});
});
module.exports = router;
Before, I got JSON Parse error: unexpected token '<', but now its JSON Parse error: unexpected identifier "var". I cant login and cant get an alert if the credentials are incorrect.
Express wasnt set up correctly and in my app file i had 'header' changed that to 'headers'.
app file
login = () => {
fetch('http://localhost:8080/users/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
"username": this.state.username,
"password": this.state.password,
})
})
.then((response) => response.json())
.then ((res) => {
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('Profile');
}
else {
alert(res.message);
}
})
.done();
}
}
express file App.js
const port = 8080;
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(port, () => console.log(`Backend now listening on ${port}!`));
module.exports = app;
express users.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'users',
port: 8889
});
router.post('/', function(req, res) {
var username = req.body.username;
var password = req.body.password;
connection.query(
"SELECT * FROM user WHERE username = ? AND password = ?",
[username, password], function (err, row){
if (err) {
console.log(err);
res.send({ 'success': false, 'message': 'Kan niet met de database verbinden'});
}
if (row.length > 0 ){
res.send({ 'success': true, 'user': row[0].username });
} else {
res.send({ 'success': false, 'message': 'Gebruiker niet gevonden'});
}
});
});
module.exports = router;
Hope this helps for people who are stuck on the same thing.

Why is my react app, which has a node and mysql backend, working locally but not on Heroku?

The home route for the initial request is "http://localhost:5000/contacts". After deploying to heroku, the UI is rendered but the data is not and I'm getting a status of 404: not found. The url shown is this one: "https://powerful-gorge-20271.herokuapp.com/contacts". I am using the Clear-DB add on on heroku as my mySql database. I have tried modifying the proxy in the react app's package.json file from "http://localhost:5000" to the heroku url but that does not work. The repo for this app is: https://github.com/aosante/React-Contact-Manager
I used this article https://daveceddia.com/deploy-react-express-app-heroku/ for guidance but it still doesn't work
This is the code in the app.js file
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const path = require('path');
const port = process.env.PORT || 4000;
const app = express();
//Static file declaration
app.use(express.static(path.join(__dirname, 'client/build')));
//production mode
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
res.sendfile(path.join((__dirname, 'client/build', 'index.html')));
});
}
app.use(cors());
const SELECT_ALL_CONTACTS = `SELECT * FROM contacts ORDER BY firstName ASC`;
//Connection creation to mysql database
const connection = mysql.createConnection({
host: 'host goes here',
user: 'user goes here',
port: 'goes here',
password: 'password goes here',
database: 'heroku_cdf7d751774d818',
insecureAuth: true
});
connection.connect(err => {
if (err) console.log(err);
});
//Server start
app.listen(port, () => {
console.log('Server started on port ' + port);
});
app.get('/api', (req, res) => {
connection.query(SELECT_ALL_CONTACTS, (err, results) => {
if (err) {
res.send(err);
} else {
return res.json({
data: results
});
}
});
});
app.get('/api/contacts', (req, res) => {
connection.query(SELECT_ALL_CONTACTS, (err, results) => {
if (err) {
res.send(err);
} else {
return res.json({
data: results
});
}
});
});
app.post('/api/contacts/add', (req, res) => {
const { firstName, lastName, email, phone } = req.query;
const INSERT_CONTACT = `INSERT INTO contacts (firstName, lastName, email, phone) VALUES ('${firstName}', '${lastName}', '${email}', '${phone}')`;
connection.query(INSERT_CONTACT, (err, results) => {
if (err) {
console.log(err);
} else {
return res.send(results);
}
});
});
app.delete('/api/contacts/delete/:id', (req, res) => {
const { id } = req.params;
const DELETE_CONTACT = `DELETE FROM contacts WHERE id = ${id}`;
connection.query(DELETE_CONTACT, (err, results) => {
if (err) {
console.log(err);
} else {
return res.send(results);
}
});
});
app.get('/api/contacts/edit/:id', (req, res) => {
const { id } = req.params;
const GET_CONTACT = `SELECT * FROM contacts WHERE id = ${id}`;
connection.query(GET_CONTACT, (err, results) => {
if (err) {
res.send(err);
} else {
return res.json({
data: results
});
}
});
});
app.put('/api/contacts/update/:id', (req, res) => {
const { id } = req.params;
const { firstName, lastName, email, phone } = req.query;
const UPDATE_CONTACT = `UPDATE contacts SET firstName = '${firstName}', lastName = '${lastName}', email = '${email}', phone = '${phone}' WHERE id = ${id}`;
connection.query(UPDATE_CONTACT, (err, results) => {
if (err) {
console.log(err);
} else {
res.send(results);
}
});
});
//production mode
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join((__dirname, 'client/build', 'index.html')));
});
}
//this goes in the end after all the requests
//build mode
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/public/index.html'));
});
And this is what's in the package.json file:
{
"name": "react-contact-manager",
"version": "1.0.0",
"description": "Simple contact manager with mysql backend",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js",
"client-install": "npm install --prefix client",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "npm install --prefix client && npm run build - -prefix client"
},
"keywords": [
"react",
"mysql"
],
"author": "Andrés Osante",
"license": "ISC",
"dependencies": {
"concurrently": "^4.1.0",
"cors": "^2.8.5",
"express": "^4.16.4",
"mysql": "^2.16.0",
"nodemon": "^1.18.9"
}
}
I also added a Procfile with "web:node app.js" written on it but that didn't help
A couple of things. The ordering of routes is important in Express--It's first come, first serve.
Since in production, you capture all your routes app.get('*', to serve your front-end, the other routes can never be hit. You need to move this toward the end of app.js after declaring your other routes.
Also, you should carefully define your routes so that there is no collision between the front and back end. I'm not sure if you are using React Router or not, but you define a get route on the root of your application ('/'). This will conflict with your front-end. This seems to be doing the same thing as /contacts, so go ahead and remove the root definition.
I'm not sure, personally, perhaps someone else can add, but in package.json in your scripts, consider redefining heroku-postbuild. I'm not sure what changing the directory might do to the app, maybe nothing. But here is another way of handling this:
"heroku-postbuild": "npm install --prefix client && npm run build --prefix client"

Can't get data form nodejs by angular

Hi I can't get data from nodejs by angular 6.
I added a service to connect between them but it is not working.
I succeed to get data by nodejs server, but I can't receive it on angular components.
I know that I missed something to connect between them but I can't resolve it.
HostingstartComponent.ts
import { Component, OnInit } from '#angular/core';
import { NgAnalyzedFile } from '#angular/compiler';
import {RouterModule ,Routes } from '#angular/router';
import {HttpModule, Http} from '#angular/http'
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SecComponent } from '../sec/sec.component';
import { ThirdComponent } from '../third/third.component';
import {aService} from '../services/a.service';
#Component({
selector: 'app-hostingstart',
templateUrl: './hostingstart.component.html',
styleUrls: ['./hostingstart.component.css']
})
export class HostingstartComponent implements OnInit {
aService: any;
data: any;
appRoutes : Routes=[
{path: 'hostingstar',component : HostingstartComponent},
{path: '',component : HostingstartComponent},
{path: 'sec',component : SecComponent, data : {some_data : 'some value'}},
{path: 'third',component : ThirdComponent, data : {some_data : 'some value'}}
];
headImg : any="assets/images/pan.JPG";
constructor(private http: Http , private service: aService) {
this.headImg ="assets/images/pan.JPG";
// this.aService.getData().then( (result) => {this.data = result; });
}
ngOnInit() {
// alert(this.aService.getData());
// this.aService.getData().then( (result) => {this.data = result; });
// alert(this.data);
}
myFunc() {
//this.router.navigate(['/third', 'north']);
// alert( document.getElementById("search-input").value);
}
getData() {
this.aService.getData().subscribe((dataFromServer) => {
this.data=dataFromServer;
// Now you can use the data
// alert(dataFromServer)
console.log(dataFromServer);
});
}
}
aService.ts
import 'rxjs/add/operator/toPromise';
import { Http, Response, Headers } from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class aService {
constructor(private http: Http) {
}
async getData() {
const options = {
headers: new Headers({
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
};
// const url = './assets/heroes.data.json';
const url = 'http://localhost:3000/';
return this.http.get(url, options)
.toPromise()
.then(response => {
if (response != null) {
const result = response.json();
return Promise.resolve(result);
}
return [];
})
.catch(err => {
console.warn('error in getCats', err);
return Promise.reject(null);
});
}
}
Node js : index.js
console.log('Running File: index.js')
//-- Create Express Server:
var express = require('express');
var app = express();
var util = require('util');
var mysql = require('mysql');
var a;
var con = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM feedback", function (err, result, fields) {
if (err) throw err;
// console.log(result);
a=result;
});
});
//-- Map Base URL to res (Response)
app.get('/', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
app.get('/hostingstar', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
//-- Listen on Port 3000:
app.listen(3000);
app.js
const express = require('express');
const app = express();
//const firebase = require('firebase-admin');
app.get('/hostingstart', (req, res) => res.send('Server Is Active!'))
app.get('/hostingstart', (req, res) => {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
connection.connect();
connection.query('SELECT * FROM feedback;', function (error, results, fields) {
if (error) {
console.warn(error);
res.send('');
return;
}
console.log("Result: " + results);
res.send(results);
});
connection.end();
})
app.get('/hostingstart', (req, res) => {
var ref = firebase.app().database().ref();
ref.once("value").then(function (snap) {
console.log("snap.val()", snap.val());
res.send(snap.val());
});
});
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");
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");
// Check if preflight request
if (req.method === 'OPTIONS') {
res.status(200);
res.end();
}
else {
next();
}
});
app.listen(3000, () => console.log('Server is listening on port 3000!'))
In your getService method you are calling the service itself not the property from the constructor.
Your:
this.aService.getData()
Should be:
this.service.getData()
Additionally call myFunc() in ngOnInit
ngOnInit() {
this.myFunc()
}