I am attempting to use middleware to catch the body of a post request, and dynamically use the message ID of the telnyx API endpoint to populate other fields, etc.
Followed the documentation here to a point, several times and cannot get the terminal to output anything but undefined when I send a message to my telnyx number: https://developers.telnyx.com/docs/v2/messaging/quickstarts/receiving-sms-and-mms
I have tried cors thinking that could be the issue from what I read in other posts, and know that express and bodyParser are no longer bundled so I used all both of those as well in an attempt to capture the data. Forgive me if it is obvious.
require('dotenv').config();
const axios = require('axios').default;
const cors = require('cors');
const telnyx = require("telnyx")("MYAPIKEY")
const express = require('express');
const app = express();
app.use(express.urlencoded( {extended: true} ));
app.use(express.json());
app.post('/webhook', (req, res) => {
console.log(`New message from ${req.body.from}: ${req.body.body}`);
});
const port = 8080;
app.listen(port, () => console.log(`App running on port ${port}`));
Here are the dependencies:
{
"name": "telnyxjs",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"telnyx": "^1.13.1"
}
}
terminal output
ngrok capture of post data
Related
Here is my code below:
Note: I am still learning typescript and the rest of the stuff so let me know for other stuff that I should do better!
Folder structure:
server.ts
import http, { createServer, IncomingMessage, ServerResponse }
from "http";
import * as app from "./app";
import * as dotenv from "dotenv";
dotenv.config();
const server = createServer(app);
server.listen(process.env.PORT);
app.ts
import express, { Application } from "express";
const app: Application = express();
const mealsRoutes = require("./routes/meals");
app.use("/meals", mealsRoutes);
module.exports = app;
meals.ts
import express, { Request, Response} from "express";
const router= express.Router();
//GET ROUTE for /meals/
router.get("/", (req: Request, res: Response, next) => {
res.status(200).json({
message:"Handling GET request to /meals"
});
});
//POST ROUTE for /meals/
router.post("/", (req: Request, res: Response, next) => {
res.status(200).json({
message:"Handling POST request to /meals"
});
});
module.exports = router;
package.json
{
"name": "restful-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node dist/server.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#types/express": "^4.17.13",
"#types/node": "^16.7.1",
"ts-node": "^10.2.1",
"typescript": "^4.3.5"
},
"dependencies": {
"dotenv": "^10.0.0",
"express": "^4.17.1"
}
}
package-lock.json: https://codeshare.io/Pd4ExY (had to share with this)
So when I run it with "node dist/server.js" and test it on the browser nothing happens, no errors, it just keeps loading. I have no clue what am I doing wrong, any help?
Make sure that the port actually is loaded correctly. If process.env.PORT ends up being undefined you get a random port. You can either add a debugger or e.g. print the port when the server has started:
const server = http.createServer(app);
server.addListener('listening', () => console.log(server.address().port));
server.listen(process.env.PORT);
The rest of the code looks fine if you are accessing the path /meals.
I've been trying to deploy my Express application on Heroku and the build gets created successfully but when I try to open it, I'm greeted with an error message that basically states that the page could not be served.
So, I run heroku logs --tail and then I get the following error messages :
One half of the error messages
Remaining half of the error messages
File Tree
Procfile
web: node server.js
Package.json
{
"name": "conduit-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.12",
"pg": "^8.7.1",
"pg-hstore": "^2.3.4",
"redux-persist": "^6.0.0",
"sequelize": "^6.6.5"
},
"devDependencies": {
"cross-env": "^7.0.3"
}
}
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { sequelize } = require('./src/entities/User/User');
const db = require('./src/config/Database');
const feedRoute = require('./src/routes/Feed/Feed');
const usersRoute = require('./src/routes/Users/Users');
const userRoute = require('./src/routes/User/User');
const articlesRoute = require('./src/routes/Articles/Articles');
const profilesRoute = require('./src/routes/Profiles/Profiles');
const commentsRoute = require('./src/routes/Comments/Comments');
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Routes
app.use('/api/feed', feedRoute);
app.use('/api/users', usersRoute);
app.use('/api/user', userRoute);
app.use('/api/articles', articlesRoute);
app.use('/api/profiles', profilesRoute);
app.use('/api/articles', commentsRoute);
// REQUESTS
app.get('/', async (req,res) => {
res.json('Yooooooooooo')
try {
await db.authenticate();
console.log('Connection has been established');
} catch(err) {
console.log('Error');
}
})
// To START sequelize and also wipes the DB clean
// async function main() {
// await sequelize.sync({force: true})
// }
// main()
// TO START sequelize
const PORT = process.env.PORT || 3000;
app.listen(PORT , () => {
console.log(`App is listening to ${PORT}`);
})
I've tried modifying my procfile and removing and re-installing the modules but the problem still persists.
I've been stuck on this for days now and any sort of help would be highly appreciated.
Looks like you problem is your pointing the main in package.json to a file that doesn't exist.
Package.json
"main": "index.js"
Your app seems to deploy from you server.js file.
The main field is a module ID that is the primary entry point to your program.
as per documentation: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main
I am hosting my very simple nodejs server in Heroku. But, when I try it, it returns this error:
Application error
An error occurred in the application and your page could not be served. If you are the application
owner, check your logs for details. You can do this from the Heroku CLI with the command`
Here's the server.js:
const express = require("express");
const cors = require("cors");
const PORT = process.env.PORT || 80;
const server = express();
server.use(cors());
server.get("/", (req, res) => {
const INDEX = "/index.html";
res.sendFile(INDEX, { root: __dirname });
});
server.get("/test", (req, res) => {
res.send("test Page");
});
server.listen(PORT, () => console.log(`listening on port ${PORT}`));
package.json:
{
"name": "express-heroku",
"version": "1.0.0",
"description": "",
"main": "server.js",
"engines": {
"node": "15.11.x"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.11.19"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
Don't know what the reason is, but, when I try this in the localhost it works perfectly!
The full error on Heroku CLI:
Any help is greatly appreciated !
Create a ProcFile:
Inside the ProcFile add web: node index.js
Doing this, you are telling heroku to run your server, with node.
I created one demo app with ReactJS, NodeJS, MongoDb and Express. Trying to deploy on heroku. It works fine, if i dont use mongo, but as soon as i introduced mongo db. I am getting error cannot GET /.
I am using mongodb atlas. Do I need heroku addon to use database?
server.js
// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const mongodb = require('mongodb');
const fs = require('fs');
const moment = require("moment");
require('dotenv').config();
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
const DATABASE_NAME = "DBNAME";
const port = process.env.PORT || 5000;
const app = express();
// Set our backend port to be either an environment variable or port 5000
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Configure the CORs middleware
app.use(cors());
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
var database, userSignUp;
app.listen(port, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
userSignUp = database.collection("UserData");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
})
package.json
{
"name": "testproject",
"version": "1.0.0",
"description": "Learning Deployment",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"client": "cd client && npm start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"npm run client\" \"npm run server\"",
"client:build": "cd client && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Username/TestProject.git"
},
"author": "Ankita Jaiswal",
"license": "ISC",
"bugs": {
"url": "https://github.com/Username/TestProject/issues"
},
"homepage": "https://github.com/Username/TestProject#readme",
"dependencies": {
"body-parser": "^1.19.0",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.7",
"moment": "^2.29.1",
"mongodb": "^3.6.3",
"mongoose": "^5.11.8"
}
}
procfile
web: npm run dev
have tried web: npm start as well.
Just from my limited experience, I've had the same issue and it turned out I forgot to configure my environment variables on Heroku, so my MONGO_URI was undefined. If not that, you can use the Heroku CLI and run heroku logs --tail from the root of your project and might be able to see more about what's going on.
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
The upper code is incorrect. You have to change < username > and < password > (both include < >) by your usename and your password! Example:
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://kanechan25:kane02052409#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
When I call a fetch post request:
fetch('http://localhost:3001/insertUser', {
method: 'POST',
mode: "no-cors",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({ a: 1 })
}).then(res => {
console.log(res)
}).then(err => {
console.log(err)
})
and receive it on the server with:
const path = require("path")
const express = require("express")
const bodyParser = require('body-parser');
const app = express()
require('dotenv').config();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/insertUser", (req, res) => {
console.log(req.body)
})
app.listen(process.env.PORT || 3001, () => {
console.log("Listening on port 3000");
});
I get an empty object, even though I am trying to send
{
a:1
}
I have
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
included in my server file and also tried changing the fetch mode to be cors instead of no-cors
package.json:
{
"name": "progression-tracker-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"env": "0.0.2",
"express": "^4.17.1",
"mongodb": "^3.6.3",
"mongoose": "^5.11.8"
}
}
The problem is caused by the no-cors option. If you remove that, then it works for me when I reproduce the code you show.
The reason for that is that no-cors only allows a limited set of headers and does not allow a content-type of application/json like you are trying to use. So, presumably that content-type is stripped by the browser and thus your bodyparser middleware does not match and doesn't do its job so the body of the post is never read and req.body ends up empty.
So, to make that type of request, you need to remove the no-cors option and if it is a cross origin request, then you need to enable that specific type of CORs request in your server or change your struture so that request isn't cross
origin.