Receive WhatsApp messages using Node.js - node.js

I'm trying to read messages from users via WhatsApp api with ultramsg
and use NGROK
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const PORT = 4000
app.use(bodyParser.json())
app.listen(PORT, () => console.log(`Server running ${PORT}`))
ngrok show display 404 error

You need Setup a webhook route
app.use(bodyParser.json())
app.post('/test_webhook', (req, res) => {
console.log(req.body)
res.status(200).end()
})
Now Webhook URL is : http://your_ngrok_url/test_webhook

Related

My nodejs server can't see my requests that I send in reactjs with axios

I'm building an application that includes react and nodejs in it..
It started yesterday, I saw that suddenly the server does not respond to the requests I sent through the axios package in reactjs..
The server just ignores.
I see that in the network window in dev tools a request to the server is sent but there is no response from the server..
I tried to put middleware in the application that will check if the server accepts sent requests:
app.use((req, res, next) => {
console.log(req.path);
next()
})
And I didn't see an answer.. it's so frustrating (I've been on this problem for two days now)
What am I doing wrong? The request is sent from an application because I see it through the network..
An important thing: I saw once that after a very long time the server received the request I sent to it.. I send a lot of requests to the server through the application, could there be an overload on the server? I don't know what to think anymore..
Also important: Sometimes the server answers my requests.. 50% of the time it returns an answer and 50% of the time it doesn't..
Server's code:
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path")
const app = express();
require("dotenv").config();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const bodyParser = require('body-parser')
const jwt = require("jsonwebtoken")
const User = require("./model/userModel")
const io = new Server(server, {
cors: {
origin: 'http://localhost:3000'
}
});
app.use(cors());
app.use((req, res, next) => {
console.log(req.path);
next()
})
mongoose.connect(process.env.MONGO_URL).then(() => {
console.log("Database Connection Successfuly.")
}).catch(err => console.log(err.message));
server.listen(process.env.PORT, () => {
console.log(`Server Started on Port ${process.env.PORT}`);
})

Express app on heroku throws authentication error on POST requests

The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})

app.get() function not getting called in node.js

So I am starting a node.js app, and familiarizing myself with the basics. I have installed express, and am using the get function to create a route and send a response.
However, on entering the webpage on the browser, the page keeps loading and does not give a response. Any idea on what I am doing wrong here? Even the request body does not show up on the logs, so it looks like its not entering the get function.
Below is the code. Any help would be appreciated.
const http = require("http");
const express = require("express");
const bodyparser = require("body-parser");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
console.log(req.body);
res.send("XYZ Homepage");
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});

"POST http://localhost:5000 net err failed"

I'm trying to send a post request to a node server using axios, here's what I've done in react-js.
axios.post('http://localhost:5000', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
And here's what I've done in the server.
const express = require('express')
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Every time I send the request, I get the following message in the console Access to XMLHttpRequest at 'http://localhost:5000/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What should I do to fix that?
Install CORS npm package to configure your express HTTP server cors.
npm install cors
Then import CORS package in your express application file like that:
const express = require('express')
const cors = require('cors')
app.use(cors())
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Then in your request code, you should to request with GET method. You are using axios.post() which does POST request. And that will response you with 404 because you don't have app.post('/') route handler in your application. So the code should look like this:
const express = require('express')
const cors = require('cors')
app.use(cors())
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
res.send(Hello ${req.body.firstName} ${req.body.lastName}!`)`;
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
You can install the cors
npm install cors --save
after that you can add this code on server file
var cors = require('cors')
app.use(cors()) // Use this after the variable declaration
You're not sending CORS headers on your responses, so the requests are denied. This can be easily solved by:
Run npm i cors
Change your code to
const express = require('express')
const cors = require('cors');
const app = express()
const port = 5000;
app.use(cors());
// all the other stuff
This error basically occurs because of a security mechanism that browsers implement called the same-origin policy. It prevents any cross-domain communication which may lead to cyber attacks like cross-site request forgery.
While we develop backend APIs for our frontend apps, we have to enable Cross-Origin Resource Sharing (CORS) in our backend server. To do that there are several libraries, the most common one is Cors package. Install it and use it in your server app as follows-
const express = require('express');
const app = express();
const port = 5000;
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World!')
})

node-fetch use get method for get a specific file content

I use node-fetch for make requests to localhost.
I want to use get method for get specific file content.
An example: my node.js server is a file called app.js, and in the same folder there is a file called config.json, so I want to get (from a discord bot made with discord.js) the content of config.json.
Here my server's code:
const express = require('express');
const app = express();
const fetch = require('node-fetch');
const fs = require('fs')
const port = process.env.port || 1451
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(`my path`, { 'Content-Type': 'text/html' });
});
app.post('/jsonFile', (req, res) => {
console.log(req.body);
})
app.listen(port, () => console.log(`listening on http://localhost:${port}`));
And here is my discord bot code for connecting to my website:
fetch('http://localhost:1451').then(res => console.log(res))
P.S I use express for node.js servers
Maybe you could use fs.readfile to read that config.json file content and then send that content as a response.

Resources