Cannot parse the string in the POST request in Express Js - javascript

I want to create a simple API with a post method in which the string will be sent as a request.On debugging I found that that the string could not be parsed on logging it was showing undefined
I have tried app.use(express.json());
Also tried middleware functions but it didn't work.
INDEX.JS
const express = require('express');
const env = require('dotenv');
const bodyParser = require('body-parser');
//importing the express module
const app = express();
//creating the app
env.config();
app.use(bodyParser());
//get request for the first page which is set to be a default
app.get('/',(req,res,next)=>{
res.send('welcome to the first page');
console.log(`welcome to the ecommerce site which is oon the ip and port np ${process.env.PORT }`);
});
app.post('/data',(request,response,next)=>{
response.status(200).json({message:request.body});
console.log(response.body);
})
//creating an which listens on port 4000
app.listen(process.env.PORT,()=>{
console.log(`application running at the port ${process.env.PORT}`);
});
on posting XYZ or 'XYZ ' or "XYZ" it is printing at localhost:4000/data
{
"message": {}
}

Related

How to Create VueJs App With WebSocket Server on Same Port

I'm a bit of a JS and Vue noob and I'm trying to figure out how to run my Vue app and a websocket server for that app on the same port 80 (to later be put behind a reverse proxy). I am able to get this working as a simple http server with express, but I can't figure out how to do it with my Vue use case.
My goal is to run a single main.js with npm run serve and bind the websocket server and routes I'm setting up with the vue router all in one application, on the same port.
Here is the example for the simple HTTP case:
server.js
'use strict';
let fs = require('fs');
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let WSServer = require('ws').Server;
let server = require('http').createServer();
let PORT = 8080
app.use(bodyParser.json());
// regular HTTP request and response
app.get('/', function(req, res) {
console.log('Get index');
fs.createReadStream('./index.html').pipe(res);
});
app.post('/', function(req, res) {
let message = req.body.message;
console.log('Regular POST message: ', message);
return res.json({ answer: 42 });
});
module.exports = app;
// Create web socket server on top of a regular http server
let wss = new WSServer({ server: server });
// Also mount the app here
server.on('request', app);
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log(`received: ${message}`);
ws.send(JSON.stringify({ answer: 42 }));
});
});
server.listen(PORT, function() {
console.log(`http/ws server listening on ${PORT}`);
});
But my question is how can I modify the default main.js vue file to do this?
import { createApp } from 'vue';
import App from './App.vue';
---
import router from './router';
import store from './store';
createApp(App).use(store).use(router).mount('#app');

Request body is empty in Post

The following is a test file written with reference to my previous question:model.save() returns an invalid output
.
// Imports
var express=require("express")
, mongoose=require("mongoose")
, bodyParser= require('body-parser')
, bodyParser = require("body-parser");
const { Int32 } = require("bson");
// Constants
const app = express()
const PORT=4002
// Create a model
const dataModel=mongoose.model('dataCollection',mongoose.Schema(data))
// Our Schema
var data={
value: Number
}
// Making connection with database
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/testdb', {
useNewUrlParser:true,
useUnifiedTopology:true
})
// Create the controller to save data
function postData(req,res){
console.log(req.body)
let newData = new dataModel(req.body)
newData.save((err,resp)=>{
if(err) console.log(err)
else res.json(resp)
})
}
// express set root page
app.get('/',(req,res)=> res.send("ROOT PAGE"));
// Set Route for our post request
app.route('/app')
.get((req,res)=>res.send("Nothing here"))
.post(postData);
// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// start listening on server
app.listen(PORT,()=>console.log(`Your application is running on Port: ${PORT}`));
The above code prints undefined for console.log(req.body) in controller function postData for the POST request shown here:
You can imagine the request is coming from the top and goes to the bottom.
It does not make sense to parse the body after you visited the route. You need to parse the body first and THEN visit the route.
// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// express set root page
app.get('/',(req,res)=> res.send("ROOT PAGE"));
// Set Route for our post request
app.route('/app')
.get((req,res)=>res.send("Nothing here"))
.post(postData);
However bodyparsers isnt used anymore. You can use instead app.use(express.json())

Why does my express router not respond to my get request?

So i have made a simple express app, but i have been trying for several hours to get a response to a simple get request when i visit http://localhost:3000/
This is my app.js
// IMPORTS
const express = require('express')
const mongoose = require('mongoose')
const customerRouter = require('./routes/customerRoute.js')
const app = express()
const PORT = 3000
// CONNECTION
mongoose.connect('mongodb://localhost/Customers', {useUnifiedTopology: true })
mongoose.connection.on('open', () => {console.log('Connected to database.')})
//APP USE ROUTES AND JSON
app.use(express.json)
app.use('/customers',customerRouter)
app.get('/', (req, res) => {
res.send('Home')
})
// APP PORT SET
app.listen(PORT)
console.log('Server started on port 3000')
This is my routes file
const express = require('express')
const router = express.Router()
console.log('into the router')
router.get('/', (req, res) => {
console.log('GET request')
})
module.exports = router
Substitute app.use(express.json) with app.use(express.json()) and everything will work. You have a mistake in this middleware that parses incoming requests with JSON payloads.
Source: express docs
You made a mistake in middleware app.use(express.json()) is a function not a property of the express object.

Express body-parser: req.body returns empty object

I've got a simple Express server that uses the body-parser module to access POST-parameters. The app looks like this:
/index.js:
'use strict';
const express = require('express');
const app = express();
const apiRouter = require('./api/routes.js');
// Set our port for the server application
const port = process.env.PORT || 8080;
// Register the routes for the /api prefix
app.use('/api', apiRouter);
// Start server
app.listen(port);
console.log('The server is running on port ' + port);
/api/routes.js:
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Configure app to use bodyParser(). This will let us get the data from a POST
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
// START ROUTES
router.post('/devices', (req, res) => {
console.log(req.body); // Returns {}
res.json(req.body);
});
module.exports = router;
The problem is that the req.body object is empty (Always returns an empty object {}). Since I already loaded the body-parser middleware I have no idea what else I can try. I hope you have any suggestions.
I used the app Postman for testing. It appeared that it sent the POST data as form-data instead of x-www-form-urlencoded. After changing this setting the data showed up.

Node, module usage structure

I've been trying to understand how to set up Stripe for my app but am having problems with the implementation of the module. Normally when using a module i would require it in the top of the file to be able to use it but I'm not sure how to do this here in the paymentController file or if i even need to. I imported the Stripe npm, so does that i mean that i can access it globally? Well as you see i'm quite new to this and would like to understand how to structure this so that the payments work.
app.js file:
angular.module('userApp', ['appRoutes', 'userControllers', 'userServices', 'ngAnimate', 'mainController', 'authServices', 'managementController', 'paymentController'])
.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptors');
});
paymentController file:
angular.module('paymentController', [])
.controller('paymentCtrl', function($scope) {
var app = this;
});
Server.js file:
var express = require('express'); // ExperssJS Framework
var app = express(); // Invoke express to variable for use in application
var port = process.env.PORT || 8080; // Set default port or assign a port in enviornment
var morgan = require('morgan'); // Import Morgan Package
var mongoose = require('mongoose'); // HTTP request logger middleware for Node.js
var bodyParser = require('body-parser'); // Node.js body parsing middleware. Parses incoming request bodies in a middleware before your handlers, available under req.body.
var router = express.Router(); // Invoke the Express Router
var appRoutes = require('./app/routes/api')(router); // Import the application end points/API
var path = require('path'); // Import path module
var passport = require('passport'); // Express-compatible authentication middleware for Node.js.
var social = require('./app/passport/passport')(app, passport); // Import passport.js End Points/API
app.use(morgan('dev')); // Morgan Middleware
app.use(bodyParser.json()); // Body-parser middleware
app.use(bodyParser.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
app.use(express.static(__dirname + '/public')); // Allow front end to access public folder
app.use('/api', appRoutes); // Assign name to end points (e.g., '/api/management/', '/api/users' ,etc. )
mongoose.connect('mongodb://localhost:27017/tutorial', function(err) {
if (err) {
console.log('Not connected to the database: ' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
// Set Application Static Layout
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html')); // Set index.html as layout
});
// Start Server
app.listen(port, function() {
console.log('Running the server on port ' + port); // Listen on configured port
});
I'd recommend following what's shown for Node in this Stripe tutorial:
https://stripe.com/docs/charges
Just like your other includes, you want something like this at the top of any JS file that will use the Stripe library:
var stripe = require('stripe')('sk_my_secret_key')
Then, elsewhere in the same file, you can call any Stripe library methods you need:
stripe.charges.create(…)
Of course, in production you'll want to build a proper 12 Factor app[1] and put your secrets in environment variables or configuration files.
[1] https://12factor.net/config

Categories