I am trying to connect with redis(of docker instance) using express(node.js).
Here is my index.ts file in which i am trying to connect with redis
import mongoose from 'mongoose'
import express from 'express'
import session from 'express-session'
import connectRedis from 'connect-redis'
import Redis from 'ioredis'
import { MONGO_URI, MONGO_OPTIONS, REDIS_OPTIONS, APP_PORT } from './config'
import { createApp } from './app';
; (async () => {
await mongoose.connect(MONGO_URI, MONGO_OPTIONS)
const RedistStore = connectRedis(session)
const client = new Redis(REDIS_OPTIONS)
const store = new RedistStore({ client })
const app = createApp(store)
app.listen(APP_PORT, () => console.log('server running on port 3000'))
})()
Here is my REDIS_OPTIONS file in which i have all redis options.
import { RedisOptions } from 'ioredis'
const {
REDIS_PORT = 6379,
REDIS_HOST = 'localhost',
REDIS_PASSWORD = 'secret'
} = process.env
export const REDIS_OPTIONS: RedisOptions = {
port: +REDIS_PORT,
host: REDIS_HOST,
password: REDIS_PASSWORD
}
docker-compose.yml
version: '3'
services:
db:
user: $UID
image: mongo
ports:
- '27017:27017'
environment:
MONGO_INITDB_ROOT: ''
MONGO_INITDB_PASSWORD: ''
MONGO_INITDB_DATABASE: auth,
MONGO_USERNAME: ''
MONGO_PASSWORD: ''
volumes:
- ./data:/data/db
- ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh:ro
cache:
image: redis:alpine
ports:
- '6379:6379'
command: ['--requirepass "secret"']
package.json
{
"name": "node-auth",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"up": "docker-compose up -d",
"postup": "npm run dev",
"stop": "docker-compose stop",
"down": "docker-compose down",
"dev": "npm run dev --prefix api"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Now when i try to run my main app file so i am getting this error
[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14) node.js
How can i get rid of this error?
Looks like it might be a problem with the Redis container. What command you used to run the container? Try adding -p 6379:6379 with your docker command. Also, check whether port 6379 is used by something else or blocked by antivirus or firewall.
change host in index.ts from 'localhost' to 'redis'
Related
I am facing
[nodemon] app crashed - waiting for file changes before starting...
While hosting my NodeJS Apollo GraphQL express server on Heroku.
It is also showing
2022-10-06T17:21:11.889722+00:00 app[web.1]: [nodemon] 2.0.20
2022-10-06T17:21:11.889912+00:00 app[web.1]: [nodemon] to restart at any time, enter `rs`
2022-10-06T17:21:11.890274+00:00 app[web.1]: [nodemon] watching path(s): *.*
2022-10-06T17:21:11.890314+00:00 app[web.1]: [nodemon] watching extensions: js,mjs,json
2022-10-06T17:21:11.890669+00:00 app[web.1]: [nodemon] starting `nodemon -r esm .`
2022-10-06T17:21:13.608667+00:00 app[web.1]: /app/node_modules/esm/esm.js:1
2022-10-06T17:21:13.616378+00:00 app[web.1]: const __global__ = this;(function (require, module, __shared__) { var __shared__;const
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Here is my index.js
import express from "express";
import mongoose from "mongoose";
import { DB, mode } from "./config";
import { ApolloServer } from "apollo-server-express";
import AuthMiddleware from "./middlewares/auth";
import * as AppModels from "./models";
import { resolvers, typeDefs } from "./graphql";
const startServer = async () => {
const PORT = process.env.PORT || 3000;
try {
const app = express();
app.use(AuthMiddleware);
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
playground: mode,
context: ({ req }) => {
let { isAuth, user } = req;
return { req, isAuth, user, ...AppModels };
},
});
mongoose.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await apolloServer.start();
await apolloServer.applyMiddleware({ app });
app.listen({ port: PORT }, () =>
console.log(`Server started at port ${PORT}`,)
);
} catch (err) {
console.log("error: "+err);
}
};
startServer();
Here is my package.json
{
"name": "forefest-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon -r esm .",
"server": "sudo systemctl start mongod && nodemon -r esm",
"dev": "nodemon -r esm"
},
"repository": {
"type": "git",
"url": "git+https://github.com/anshuman-8/forefest-backend.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/anshuman-8/forefest-backend/issues"
},
"homepage": "https://github.com/anshuman-8/forefest-backend#readme",
"dependencies": {
"apollo-server-express": "^3.10.2",
"bcryptjs": "^2.4.3",
"consola": "^2.15.3",
"dotenv": "^16.0.2",
"esm": "^3.2.25",
"express": "^4.18.1",
"graphql": "^16.6.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"mongoose": "^6.6.1",
"mongoose-paginate-v2": "^1.7.1",
"nodemon": "^2.0.20",
"yup": "^0.32.11"
}
}
I have tried multiple ways of fixing this problem, Please help me.
This is my first time deploying a server.
I'm generating migrations using TypeOrm in NestJS but I don't know why it creates the migration file at the root every time and I want it to automatically create the migration file into /src/server/migration/ folder.
ormconfig.ts
import * as dotenv from 'dotenv';
import { DataSource } from 'typeorm';
dotenv.config();
const connection = new DataSource({
type: 'postgres' as const,
host: 'localhost',
port: 5432,
username: 'username',
password: 'password',
database: 'database',
entities: ['src/server/entity/*.{ts,js}'],
migrations: ['src/server/migration/*.{ts,js}'],
extra: {
ssl: false,
},
});
export default connection;
package.json
{
"scripts": {
"typeorm": "typeorm-ts-node-esm --dataSource ./ormconfig.ts",
"migration:gen": "npm run typeorm migration:generate -n",
},
"dependencies": {
"typeorm": "^0.3.6",
}
}
I am using nodemailer with my Firebase Functions (server-side functions) for my React.js project and am getting the error: Error: Client network socket disconnected before secure TLS connection was established... and causing some emails to not be sent out. This is a big issue for this project, as the client can't be missing emails sent from the system. Why am I getting this error and how might I remedy it?
Firebase Function index.js:
"use strict";
import functions = require('firebase-functions');
import admin = require("firebase-admin");
import nodemailer = require('nodemailer');
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';
import { Change, EventContext } from 'firebase-functions';
import { Status } from './common';
admin.initializeApp(functions.config().firebase);
export const onUserCreated = functions.firestore.document('users/{userId}')
.onCreate(async (snap: { data: () => any; }) => {
console.log("Client create heard! Starting inner...")
const newValue = snap.data();
try {
console.log("Started try{}...")
// Template it
const htmlEmail =
`
<div>
<h2>client Sign Up</h2>
`
// Config it
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: functions.config().email.user,
pass: functions.config().email.password
}
})
console.log("transporter = " + transporter)
// Pack it
const mailOptions = {
from: `email123#gmail.com`,
to: 'email123#gmail.com',
replyTo: `${newValue.email}`,
subject: `user sign up`,
text: `A new user sign up with the email of ${newValue.email}.`,
html: htmlEmail
}
// Send it
transporter.sendMail(mailOptions, (err: any) => {
if(err) {
console.error(err);
} else {
console.log("Successfully sent mail with sendMail()!");
}
})
} catch (error) {
console.error(error)
}
});
Functions package.json:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"main": "lib/index.js",
"dependencies": {
"#types/nodemailer": "^6.4.0",
"firebase-admin": "^9.4.1",
"firebase-functions": "^3.11.0",
"nodemailer": "^6.4.16"
},
"devDependencies": {
"firebase-functions-test": "^0.2.3",
"tslint": "^5.12.0",
"typescript": "^3.8.0"
},
"private": true
}
Full error:
In my case the error gone after adding TLS version to nodemailer options:
let transporter = nodemailer.createTransport({
host: 'smtp-server',
port: 25,
tls: {
ciphers : 'SSLv3',
},
});
You should return a promise to avoid unexpected Fuctions behaviour like early termination.
Checking Nodemailer API documentation
I can see that transporter.sendMail returns a promise. So just returning this promise should fix your issue:
export const onUserCreated = functions.firestore.document('users/{userId}')
.onCreate(async (snap: { data: () => any; }) => {
....
return transporter.sendMail(mailOptions)
}
What I am trying to do: I am trying to practice MERN structure, so I wanted to set up a node.js server and react front-end first.
However, what happened is that when the server gets fired, the entire DOM got overwrite, why is that?
server.js is a simple node.js
const express = require('express');
const app = express();
// console.log that your server is up and running
app.listen(3000, () => console.log(`Listening on port 3000`));
// create a GET route
app.get('/test', (req, res) => {
res.send({ express: 'I MADE IT' });
});
React.js is my front-end:
import React from 'react';
import logo from './img/nav-logo.png';
import Product1 from './img/manage.png';
import Product2 from './img/deliver.png';
import Product3 from './img/market.png';
import Service from './service.js'
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends React.Component {
constructor(props){
super(props)
this.state={
items: [{
desc:"Manage",
price: 5000,
purchased: false,
},
{
desc:"Deliver",
price: 2000,
purchased: false,
},
{
desc:"Market",
price: 4000,
purchased: false,
}
],
data:null,
}
}
componentDidMount() {
console.log("here")
this.callApi()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
callApi = async () => {
const response = await fetch('/test');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
handleClick(desc){
const newItems = this.state.items.slice()
this.printItems(newItems)
for(var item of newItems){
if(item.desc === desc){
item.purchased = !item.purchased
}
}
this.printItems(newItems)
this.setState({
items: newItems
})
}
printItems(items){
console.log(items[0].purchased + " " + items[1].purchased + " " + items[2].purchased)
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to Shopping Center</h1>
</header>
<div>
<div>
{this.state.data} //<------------trying to render the data here
</div>
<Service url={Product1} desc="Manage" alt="MA" purchased={this.state.items[0].purchased} thisClick={ (desc) => this.handleClick("Manage")} />
<Service url={Product2} desc="Deliver" alt="DE" purchased={this.state.items[1].purchased} thisClick={ (desc) => this.handleClick("Deliver")}/>
<Service url={Product3} desc="Market" alt="MR" purchased={this.state.items[2].purchased} thisClick={ (desc) => this.handleClick("Market")}/>
</div>
</div>
);
}
}
export default App;
Without my node.js running, i can render my react just fine.
However, once I do npm server.js. localhost:3000 will no longer work. So i treid localhost:3000/test, and the entire HTML became the string "{ express: 'I MADE IT' }"
My index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
I want to render the message as part of my regular React DOM, but somehow the node server overwritten my entire front-end.
Additionally, i got an error message in console state the following:
SyntaxError: Unexpected token < in JSON at position 0
at App._callee$ (App.js:42)
at tryCatch (runtime.js:62)
at Generator.invoke [as _invoke] (runtime.js:296)
at Generator.prototype.(:3000/anonymous function) [as next] (http://localhost:3000/static/js/bundle.js:31252:21)
at step (App.css?9a66:26)
at App.css?9a66:26
The line of code that I located is the componentDidMount() method
My package.json file:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^4.1.3",
"express": "^4.16.3",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-scripts": "1.1.5",
"reactstrap": "^6.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:3001"
}
For development, given you are using create-react-app for your React application, you can use a development proxy to run both Express and React on separate ports. Any fetch() requests will be redirected to the specified proxy path/port in package.json. This will allow you take advantage of development tools for each platform.
Change the Express server port to anything other than 3000. For example app.listen(3001, () => console.log('Listening on port 3001')); This is so create-react-app can run on 3000 and Express can run on 3001.
Added the following line to the React application's package.json to enable a proxy, "proxy": "http://localhost:3001". A fetch request to /api/test will be redirect to http://localhost:3001/api/test.
For production, given you would want both applications to run on the same port:
Set up static resource loading for the server using static() method.
Added logic to server to redirect all requests that do not match you "API" paths, to load the index.html of the production built npm run build React application using sendFile(). This will allow to use routing within the React application.
Here is what that could look like at a basic level, with the create-react-app build folder generated from npm run build command is placed into path /public/build:
app.use(express.static(path.join(__dirname, 'public', 'build')));
// API route
app.get('/api/test', (req, res) => {
res.send({ express: 'I MADE IT' });
});
// catch-all route
app.use('*', function (request, response) {
response.sendFile(path.join(__dirname, 'public', 'build', 'index.html'));
});
React fetch():
// ...
const response = await fetch('/api/test'); // this matches the path specified on server, before the catch all route
const body = await response.json();
// ...
Check out this answer as it was a similar issue.
Update: - Steps to create simple Express + React development environment:
Create Express application using express-generator. Run command npx express-generator react-express
Navigate into created project. Run command cd react-express.
Run command npm install. Then delete directory public.
Create React application using create-react-app. Run command npx create-react-app public.
Install concurrently. Run command npm install concurrently --save-dev.
Edit app.js at the base of project created by express-generator. Add the following lines starting at line 25. This is to expose and endpoint at /api/test and provide a "catch-all" route to load index.html generated by npm run build.
```
app.get('/api/test', (req, res) => {
res.send({ express: 'I MADE IT' });
});
app.use('*', function (request, response) {
response.sendFile(path.join(__dirname, 'public', 'build', 'index.html'));
});
```
Edit /bin/www line 15 to change port from 3000 to 3001. var port = normalizePort(process.env.PORT || '3001');
Edit package.json created by create-react-app at /build/package.json. Add the following line "proxy": "http://localhost:3001".
At the base package.json located at the root of the project, created by express-generator, add the following line to srcipts: "dev": "concurrently \"node ./bin/www\" \"cd public && npm start\""
Run command npm run dev from the base of the project. This will load both the server (Express) and client (React) and will proxy calls, in this example /api/test on port 3000 will be directed to the server port running at 3001.
Hopefully that helps!
I try to get my feet wet implementing a simply webhook for Google's NLP API.AI interface. I want to use Heroku as the server using node.js. The problem is that I can build and deploy the code on Heroku but the execution fails immediately.
Extract from the build log (note that the "real name" app is not test, I just changed it for this post)
[...]
2017-07-21T13:28:57.000000+00:00 app[api]: Build succeeded
2017-07-21T13:29:07.012028+00:00 heroku[web.1]: Starting process with command `npm start`
2017-07-21T13:29:10.516218+00:00 app[web.1]:
2017-07-21T13:29:10.516234+00:00 app[web.1]: > test#0.0.3 start /app
2017-07-21T13:29:10.516235+00:00 app[web.1]: > node app.js
2017-07-21T13:29:10.516236+00:00 app[web.1]:
2017-07-21T13:29:11.076809+00:00 heroku[web.1]: State changed from starting to crashed
I have tried many different versions of code but even this code which is reduced to pretty much nothing fails to execute.
Here is my app.js:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
const ApiAiApp = require('actions-on-google').ApiAiApp;
const test = function(request, response) {
// todo
};
module.exports = {
test
};
And this is the package.json file:
{
"name": "test",
"description": "virtual scrum master",
"version": "0.0.3",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"scripts": {
"lint": "semistandard --fix \"**/*.js\"",
"start": "node app.js",
"monitor": "nodemon app.js",
"deploy": "gcloud app deploy"
},
"engines": {
"node": "6.11.1"
},
"dependencies": {
"actions-on-google": "^1.0.0"
},
"devDependencies": {
"semistandard": "^9.1.0"
}
}
After a log of searching I found the correct setup.
Here is the correct app.js code:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json({type: 'application/json'}));
app.post('/', function (req, res) {
// Todo
});
if (module === require.main) {
// Start the server
let server = app.listen(process.env.PORT || 8080, function () {
let port = server.address().port;
console.log('App listening on port %s', port);
});
}
module.exports = app;