I'm recently doing tests with the venom-bot library for whatsapp, but when executing the "action" action in my browser, it only runs once, after that it doesn't send a message to any number! I can't find where I'm going wrong.
const express = require('express');
const venom = require('venom-bot');
const bodyParser = require('body-parser');
venom
.create({
session: 'randomsession', //name of session
multidevice: true // for version not multidevice use false.(default: true)
})
.then((client) => start(client))
.catch((erro) => {
console.log(erro);
});
async function start(client) {
const app = express();
const PORT = 3333;
app.use(bodyParser.json())
app.get("/enviarcode", async (req, res, next) => {
await client.sendText(req.query.number + "#c.us", req.query.message);
res.json(req.query);
})
app.listen(PORT, () => {
console.log(`Online on Port ${PORT}`)
})
}
Related
https://github.com/skyturkish/e_commerce_advance this is the repo
index.js
const express = require('express')
const bodyParser = require('body-parser')
const UserService = require('./services/user-service')
const app = express()
app.set('view engine', 'pug')
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.render('index')
})
app.get('/users/all', async (req, res) => {
const users = await UserService.findAll()
res.render('user', { users })
})
app.get('/users/:id', async (req, res) => {
const user = await UserService.find(req.params.id)
res.send(user)
})
app.post('/users', async (req, res) => {
const user = await UserService.add(req.body)
res.send(user)
})
app.delete('/users/:id', async (req, res) => {
const user = await UserService.del(req.params.id)
res.send(user)
})
app.listen(3000, () => {
console.log('Server listening')
})
When I try to add a new user under "http://localhost:3000/" or "http://localhost:3000/users/all", this works. But under http://localhost:3000/users/1 throw an error. I cant understand well, why this happens, how does being under a domain authorize and receive it.
The GET handlers for / and /users/all use res.render(), but the GET handler for /users/:id uses res.send() (so it doesn't render your template, which in turn loads the axios library).
I am testing a user registration route but its returning a Cannot POST /api/user and it seems i can't pin point the problems.
when I run a get request using postman, it works...but when I post, it returns a Cannot POST /api/user result .
Any sort of help/response will be greatly appreciated.
here is my server.js file.
const express = require('express');
const mongosse = require('mongoose');
const bodyParser = require('body-parser');
//const entries = require('./routes/api/entries');
const app = express();
const path = require("path")
//app.use(bodyParser.json());
app.use(express.json())
//const db = require('./config/keys.js').mongoURI;
mongosse
.connect('mongodb+srv://user:pass2i8y7#gytay.qpgpm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex:true
})
.then(() => console.log('its connected'))
.catch(err => console.log(err));
app.use('/api/entries', require('./routes/api/entries'));
app.use('/api/user', require('./routes/api/user'));
//serve a static dish of data
if (process.env.NODE_ENV == 'production') {
//set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname,
'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
And here is my User route.
const express = require('express');
const router__ = express.Router();
//User model
const User = require('../../models/User');
//#Post api/users
//#desc register user/s
router__.post('/', (req, res) => {
res.send('regesiter__here');
});
module.exports = router__;
I couldn't find any problem with the code so, i ended up restarting the server and it worked! everything good
I create routes on Express js in Next js. When i deployed on hosting and sent request on route i getting error 405, but when i do same on localhost everything all right.
I cant understand that is this?
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
nextApp.prepare().then(() => {
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const apiRoutes = require("./routes");
app.use('/api', apiRoutes)
app.get('*', (req,res) => {
console.log('asdfasdfasdfd')
return handle(req,res)
})
app.listen(PORT, err => {
if (err) throw err;
console.log(`ready at http://localhost:${PORT}`)
})
})
I think your express config has problem.
your express server must be like this:
const express = require('express')
const next = require('next')
const handler = routes.getRequestHandler(app)
const app = next({ dir: '.', dev })
app.prepare().then(() => {
const server = express()
server.post('/api', (req, res) => {
handler(req, res, req.url)
)
server.get('*', (req, res) => {
handler(req, res, req.url)
})
}
check the code for server.get and server.post or other http methods.
Error 405 tells that the method is not allowed.
Vercel can't use custom server with next js
https://github.com/vercel/next.js/discussions/13306
I'm refactoring the following code :
require('dotenv').config();
// Express App Setup
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const cors = require('cors');
const uuid = require('uuid/v4');
// Config
const config = require('./config');
// Initialization
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Postgres client
const { Pool } = require('pg');
const pgClient = new Pool({
user: config.pgUser,
host: config.pgHost,
database: config.pgDatabase,
password: config.pgPassword,
port: config.pgPort
});
pgClient.on('error', () => console.log('Lost Postgres connection'));
pgClient
.query(
`
CREATE TABLE IF NOT EXISTS items (
id uuid,
item_name TEXT NOT NUll,
complete BOOLEAN DEFAULT false,
PRIMARY KEY (id)
)
`
)
.catch(err => console.log(err));
// Express route handlers
app.get('/test', (req, res) => {
res.send('Working!');
});
// Get all to do list items
app.get('/v1/items', async (req, res) => {
...
});
// Get a single todo item
app.get('/v1/items', async (req, res) => {
...
});
// Create a todo item
app.post('/v1/items', async (req, res) => {
...
});
// Update a todo item
app.put('/v1/items/:id', async (req, res) => {
...
});
// Delete a todo item
app.delete('/v1/items/:id', async (req, res) => {
..
});
// Server
const port = process.env.PORT || 3001;
const server = http.createServer(app);
server.listen(port, () => console.log(`Server running on port ${port}`));
Into a controller & routes usage , as follows :
New index.js :
require('dotenv').config();
const itemRoutes = require('./routes/itemRoutes');
// Express App Setup
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const cors = require('cors');
const uuid = require('uuid/v4');
// Config
const config = require('./config');
// Initialization
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Postgres client
const {Pool} = require('pg');
const pgClient = new Pool({
user: config.pgUser,
host: config.pgHost,
database: config.pgDatabase,
password: config.pgPassword,
port: config.pgPort,
});
pgClient.on('error', () => console.log('Lost Postgres connection'));
pgClient
.query(
`
CREATE TABLE IF NOT EXISTS items (
id uuid,
item_name TEXT NOT NUll,
complete BOOLEAN DEFAULT false,
PRIMARY KEY (id)
)
`
)
.catch((err) => console.log(err));
// Express route handlers
app.get('/test', (req, res) => {
res.send('Working!');
});
// middlewares
app.use('/v1', itemRoutes);
// Server
const port = process.env.PORT || 3001;
const server = http.createServer(app);
server.listen(port, () => console.log(`Server running on port ${port}`));
New itemRoutes.js
const express = require('express');
const router = express.Router();
const {
createItem,
getSingleItem,
getAllItems,
updateItem,
deleteItem,
} = require('../controllers/item');
router.get('/items', createItem);
router.get('/items', getSingleItem);
router.post('/items', getAllItems);
router.put('/items/:id', updateItem);
router.delete('/items/:id', deleteItem);
module.exports = router;
New Controller - The Controller uses the PgClient:
exports.getAllItems = async (req, res) => {
...
};
exports.getSingleItem = async (req, res) => {
...
};
exports.createItem = async (req, res) => {
...
};
exports.updateItem = async (req, res) => {
...
};
exports.deleteItem = async (req, res) => {
...
};
The PgClient is created in the Index.js.
The problem is , how can I pass the PgClient to a controller , without creating a new instance of the PgClient every time ?
I am trying to serve an angular app using nodejs. But i get this error
"Cannot GET /" in the body of the page. I tried a number of things but still this does not work. do you folks have any suggestion?
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
app.listen(5000, () => console.log('Listening on port 5000'))
////////////////////////////////////////
// View
////////////////////////////////////////
const viewOptions = { include_docs: true }
app.route('/api/schedules').get((req, res) => {
couchDb.getType('schedule', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/stations').get((req, res) => {
couchDb.getType('station', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/tests').get((req, res) => {
couchDb.getType('testConfig', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
you are missing your routes e.g
app.get('/', function (req, res) {
res.send('hello world')
})
or you need to include your all routes through middle ware.
You are getting that error because you are not declaring any endpoints or telling the server to serve anything. It is listening on port 5000, but no responses to any urls have been defined. Here is a piece of example code that will resolve your issue.
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
// This block will make it so that every path on port 5000 responds with "Hello, World!"
app.get('*', (req, res) => {
res.status(200).send("Hello, World!");
});
app.listen(5000, () => console.log('Listening on port 5000'))
This will make it respond with basic text, if you want to serve an angular application, you will need to look into serving static content from express: https://expressjs.com/en/starter/static-files.html
You have to use a routing middleware and map your modules to the required modules.Also make sure your modules are mounted in router instance.
Something like
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
//All requests with /schedules will go to './modules/schedules'
app.use('/schedules', schedules);
app.use('/stations', stations);
app.listen(5000, () => console.log('Listening on port 5000'))
your ./modules/station should look like
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('You are in /station')
})
router.get('/new', function (req, res) {
res.send('You are in /station/new')
})
module.exports = router
For more : https://expressjs.com/en/guide/routing.html