Can not post to server using node express - node.js

I am trying to post data from postman to my node server, I keep getting 404.
Is my code setup correctly to receive post to http://localhost:8080/back-end/test and if not how can I fix it ?
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
var firstFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
app.post('back-end/test.js', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
}, 2000);
});
};
I am posting LoginEmail and keep getting 404.

Move app.post() outside of the timeout, promise, and firstFunction.
There is no proceeding paths defined in your code, so the path must start with a /: /back-end/test.js. Don't forget the extension since you've defined it.

Related

Ionic/Angular not connecting properly to nodeJS (routes work perfectly in postman

I am able to run the GET & POST requests using POSTMAN, and it works. I cannot figure out where I'm going wrong in my app. My GET request to the same address works just fine.
Ex., In my service:
createOne(route, document) {
console.log(`create new ${route}`, document);
console.log(`http://localhost:8080/api/${route}`);
return this.http.post(`http://localhost:8080/api/${route}`, document);
}
This logs in the console as:
Unfortunately, it doesn't log a thing on the nodeJS server, so I'm sure I made a mistake somewhere in the server.js file - but can't figure out where!
POST request via postman to http://localhost:8080/api/appts with this for raw JSON body:
{
"title": "test from postman",
"description": "test description",
"startTime": "2020-08-04T17:40:45.521-04:00",
"endTime": "2020-08-04T20:10-04:00",
"allDay": false
}
My server.js file:
//1. require express and call it as a function
require('./api/data/db.js');
const cron = require('node-cron');
var express = require('express');
console.log(process.env.PORT);
var app = express();
var cors = require('cors');
var path = require('path');
var bodyParser = require('body-parser');
var routes = require('./api/routes');
var json2xls = require('json2xls');
//PORT SETUP
if (process.env.PORT) {
app.use(cors());
app.set('port', process.env.PORT || 8080);
} else {
app.set('port', 8080);
}
// MIDDLEWARE
app.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
app.use(json2xls.middleware);
// ROUTING
app.use(express.static(path.join(__dirname, 'app/www'))); //setup primary route request folder
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));
app.use(bodyParser.urlencoded({ extended: true })); //only get strings and arrays from form when false
app.use(bodyParser.json()); // tell backend to understand json data
app.use('/api', routes);
// LOAD THE SINGLE PAGE FOR IONIC
app.get('*', function (req, res) {
res.sendFile('/app/www/index.html', { root: __dirname });
});
// START SERVER LISTENING
var server = app.listen(app.get('port'), function () {
var port = server.address().port; // return the port for the server listening
console.log('RayWood API running on port ' + port); //confirm app running
});
My File Tree is setup as follows:
Seeing how the nodeJS server doesn't log the URL or REQUEST, I think the problem is in my server.js file - but I still don't know what I did wrong. Please help!
You are not subscribing to Observable .If you are not familiar with Observable You can convert it to Promise please use below sample implemenation
createOne(route, document) {
console.log(`create new ${route}`, document);
console.log(`http://localhost:8080/api/${route}`);
return new Promise((resolve, reject) => {
this.http.post(`http://localhost:8080/api/${route}`,document).subscribe((resp)=>{
console.log(resp);//This is the response from Node API
resolve(resp);
},(err)=>{
reject(err)
});
});
}

Both POST/GET requests yield a 404 error in Postman. Is my Express routing to blame?

I am intending to set up a Node.js server with MongoDB to handle HTTP CRUD requests. Upon setting up my endpoint I was initially able to receive POST/GET requests, however the handling of the document objects became the issue. Upon trying to fix this issue I am now unable to POST/GET at all? Is this simply a syntax issue or is my code doomed?
const MongoClient = require('mongodb').MongoClient;
var QRCode = require('qrcode');
var canvasu = require('canvas');
var express = require('express');
var mongoose = require('mongoose')
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var db;
var collection
var Patient = require('./ShiftAssist/models/patientModel');
var router = express.Router();
''
CODE FOR CONNECTION
''
router.get('/patients/:Pnum', function(req,res,next){
Patient.findOne({Pnum:req.params.Pnum},function(err,patient){
if (err) return next(err);
res.json(patient);
})
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port ' + port + '!');
});
Expected: GET request to http://127.0.0.1:3000/patients/XXXXXX with a document identifier, returns entire document
Actual: Timeout Error
try to change you route by /patients/:Pnum
and your request should be http://127.0.0.1:3000/patients/XXXXXX
source: https://expressjs.com/en/guide/routing.html
EDIT: Code i used so far
var express = require('express');
var app = express();
var router = express.Router();
router.get('/patients/:Pnum', function (req, res, next) {
setTimeout(() => res.json({ ok: req.params.Pnum }), 1000)
});
app.use('/', router);
app.listen(3000);

BodyParser data is undefined after AJAX call

The body parser body is {}. I've already done research and made sure that my ajax data key is set correctly as well as make sure the middleware is set up correctly as well. Here is my frontend ajax call
$.ajax({
type:"GET",
url:"/api",
data: {course:"MATH-226"},
success: function(data){ alert(data);}
});
And here is my backend server.js file:
'use strict'
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const alg = require('./app/algorithm.js');
const app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/api', (req, res) => {
console.log(req.body);
alg.create(req.body.course, answer => res.send(answer));
});
let server = app.listen(3000, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You are using a GET request, so it's probably not being sent. If you need to send something, you can attach it as a header or include it in the query string of the url. If you want to send data, I would use a POST request.
Check out this article
How to send data in request body with a GET when using jQuery $.ajax()

Express POST request.body undefined

I am trying to make POST work with Express (4.13.3 version). when I print request.body.user, it says 'undefined'. I am using Chrome Poster to post my JSON request. Here is how my request looks
{
"user":"testUser",
"password":"test pwd"
}
the URL I use: http://localhost:4000/first
and my server.js file.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/first', function (request, response) {
console.log('FIRST POST hello world');
console.log('req.body:' + request);
var user_name=request.body.user;
var password=request.body.password;
console.log("User name = "+user_name+", password is "+password);
response.end("yes");
});
var server = app.listen(4000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
when I post the request, here is what I see on my Node console.
Example app listening at http://:::4000
FIRST POST hello world
req.body:[object Object]
User name = undefined, password is undefined
Why I am not able to get my 'user' and 'password' values here from my request? I am getting 'undefined' for both of these variables.
try this:
app.use(bodyParser());
if this still doesn't work change your request to this:
user=testUser&password=test+pwd
This is how the request body have to look using Chrome's "Advanced REST Client".

Node.js code does not execute

I have written some Node.js code but when I run node index.js in my terminal it's just blank. My Node script does not even log to the console after creating the server or is responding with my index.html file. I even tried changing all 'req' and 'res' to 'request' and 'response'. Here's my code:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({ extended: false });
http.createServer(function(request, response){
console.log('listening on port 8080');
app.on('request', function(request, response){
response.sendFile('./index.html');
});
app.post('/auth', urlparse, function(request, response){
var user = request.body.user;
var pass = request.body.pass;
});
}).listen(8080);
Pleas help. Thanks in advance.
EDIT: Anything inside the http.createserver(); does not execute because I tried logging another sentence outside the http.createServer(); and it logged!
Go ahead and try the following:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({extended: false});
app.on('request', function (request, response) {
response.sendFile('./index.html');
});
app.post('/auth', urlparse, function (request, response) {
var user = request.body.user;
var pass = request.body.pass;
});
// Bind createServer with app:
http.createServer(app).listen(8080, function (request, response) {
console.log('listening on port 8080');
});
I expect that this should work for you.
Update:
The method mentioned, while works, has become outdated.
the recommended method is:
app.listen(8080, function () {
console.log('listening on port 8080');
});
Using this method allows you to skip requiring http.

Resources