I've just started learning Express and Servers.
Problem
Just wanted to load another EJS page onto my localhost:4000/ path as a response after a POST request has been made for a form.
However, although I do get the response of the EJS page with the data from the req.body in the form from the client-side. I can't seem to get the page to load on the browser.
Any ideas? pls help
Express.js Server
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let path = require('path');
let fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({extended:true});
app.use(express.json());
app.set('view engine', 'ejs');
app.use('/', express.static(__dirname + '/views'));
app.use('/', express.static(__dirname + '/views/partial'));
//Handling the GET request with the render of EJS file "index"
app.get('/', (req, res)=> {
res.render('index');
});
//Handling the POST request from the client, and sending the EJS file "createAccount" as a response
app.post('/', urlencodedParser, (req, res) => {
res.set('cache-control', 'max-age=0; private; no-cache');
res.render('createAccount', {data:req.body}); //
});
app.listen(4000, ()=>{
console.log('Port 4000 has been called');
});
EDIT:
I've included the JS file which I am using to make the POST request below.
document.querySelector('#btn').addEventListener('click', Master);
async function Master(){
console.log("Button clicked")
const username = document.querySelector("#username").value;
const password = document.querySelector("#password").value;
let results = {
"username": username,
"password": password
};
console.log(results);
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(results)
};
const post = await fetch('/', options);
};
I don't know if this is a correct question lol but is it ok to have the same "/" in get and post request? Why not put something in it.
app.post("/create")
then also change this
const post = await fetch('/create', options);
Related
I am trying to read the body of POST request using Express in Node.JS framework. I send a HTTP POST request using HTML form. I detected a POST request on WireShark with the following data:
This shows that the request is sent successfully. I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn't seem to work no matter what I tried. My current implementation goes like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()
//Import static files
app.use(express.static('../public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', jsonParser, (req, res) => {
console.log(req.body);
res.send(200);
});
app.listen(port, () => console.log("Server started"));
No matter what I try from other posts, it still does not seem to return me any data.
Does anyone have an idea how to fix this problem?
Why to you use 'jsonParser' in the app route? Try something like:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post-test', (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});
I'm trying to follow this documentation from Stripe: https://stripe.com/docs/connect/standard-accounts
I'm stuck on point 4 where I am trying to authorize a user and get a response with an access token.
I am using a express backend in a React app and I have the following set up in my server.js file:
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '..', 'public');
var TOKEN_URI = 'https://connect.stripe.com/oauth/token';
var CLIENT_ID = 'xxxx'
var API_KEY = 'STRIPE_API_KEY'
app.use(express.static(publicPath));
app.get('/api/callback', function(req, res) {
var code = req.query.code;
request.post({
url: TOKEN_URI,
form: {
grant_type: "authorization_code",
client_id: CLIENT_ID,
code: code,
client_secret: API_KEY
}
}, function(err, r, body) {
var accessToken = JSON.parse(body).access_token;
console.log(accessToken);
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
I've removed my port number and listening reference but this is in place.
So when I test with Stripe and go my callback page I get an Internal Server Error but I am not sure what is causing this and why I am getting no response back from my console.log?
Thanks.
I think you need to import the request library at the top
const request = require('request');
Also please make sure your package.json file contains request library if not please install it first. https://www.npmjs.com/package/request
I'm trying to send a POST request to my API using the request module but i get nothing back and when i console log the request data i see the fields are undefined as shown in the image below. Dont know why.
I've tried to solve the issue but no success. I don't know what is wrong. But when i try to send data to the same API via POSTMAN it works fine as seen in the image below. So i dont know why its not working when i send data from the front end of my app
i need help in figurig this out.
Heres's my server side code
let express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
//connect = require('connect'),
jobRoutes = require('./routes/jobs'), //ddd
// db = require('./models/app'), //ddd
// helpers = require('./helpers/jobs'),
// fetch = require("node-fetch"),
path = require('path'),
router = express.Router(),
app = express(),
port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.use(express.static(path.join(__dirname + '/public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/api/jobs', jobRoutes);
app.post('/jobs', (req, res)=>{
let formBody = {
title: req.title,
category: req.body.category,
description: req.body.description,
type: req.body.type,
url: req.body.url,
email: req.body.email,
apply: req.body.apply,
location: req.body.location,
company: req.body.company,
createdAt: Date.now()
};
request.post(console.log(formBody),{url:'http://localhost:3000/api/jobs/', form: formBody
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}else{
console.log('Upload successful! Server responded with:', body);
}
return res.redirect('/jobs')
});
})
app.listen(port, process.env.PORT, process.env.IP, ()=> console.log(`Server is running on ${port}`))
And here's what the receiving end server code looks like
let db = require ('../models/app');
exports.createJob = (req, res) => {
console.log('The req body:',req.body)
db.Job.create(req.body)
.then((newJob) => {
res.status(201).json(newJob)
})
.catch((err) => {
res.send(err)
})
}
You can checkout the current repo for more clarity
But when i try to send data to the same API via POSTMAN it works fine as seen in the image below.
The image shows that the Content-Type of the request from Postman will be application/json but the code using the request module is going to send one with a Content-Type of application/x-www-form-urlencoded.
Presumably (your "receiving end server code" does not show the bodyParser), your server only supports JSON formatted requests.
Either configure the server to support application/x-www-form-urlencoded or make the request send JSON.
I'm currently trying to implement file-uploads for my application, in which I use ReactJS, node.js with express, and MongoDB and mongoose. I'm using multer middleware for fileuploads, however, despite looking at all similar questions here on SO and also looking it up, I can't seem to get it to work.
This is my React form:
addUser (event) {
var formfile = new FormData();
formfile.append("file", this.state.filesToBeSent);
axios.post('adduser',
JSON.stringify({
entry: this.state.currname,
passwrd: this.state.currpasswrd,
formfile : formfile
}), {
headers: {"Content-Type": "application/json"}
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<form onSubmit={this.addUser} encType="multipart/form-data" >
<input value={this.state.currname} />
<input value={this.state.currpasswrd} />
<input type="file" value={this.state.filesToBeSent} name="file" />
<button type="submit" >Add</button>
</form>
);
}
This is my node.js file:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = require('../models/User.js');
var bodyParser = require('body-parser');
var multer = require("multer");
const uuidv4 = require("uuid/v4");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cd(null, "./uploads");
},
filename: (req, file, cb) => {
const newFilename = `${uuidv4()}${path.extname(file.originalname)}`;
cb(null, newFilename);
},
})
const upload = multer({ storage });
router.post("/", upload.single("file"), (req, res) => {
console.log(req.file + " and exit.");
});
module.exports = router;
I'm not doing anything with the text-inputs just yet, because I wanted to get the file upload to work first.
I tried out a variety of things, like using async(req, res) in router.post(). I tried using x-www-form-urlencoded as content-type and to only send the file without text-inputs( I specified formfile as data to be sent without the whole JSON.stringify(), however, I didn't manage to get it to work.
Can anyone spot a mistake in my code? Or does anyone have any other ideas about how to get it to work?
Edit:
Setting up the adduser-route in app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var adduser = require('./routes/adduser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/adduser', adduser);
Did you test your post endpoint? You can use a rest client such as Postman or Insomnia just to make sure that this is not the problem. Send a POST request to the endpoint and see if it gets invoked.
Then I guess you should use "/adduser" on your client and not "adduser" if you endpoint is exposed at "localhost:port/adduser". Your code doesn't show how you set up the route in the node.js code.
Finally you may want to use an higher level component to perform the upload, which can handle multipart for you in case you upload larger files. I found the combination react-dropzone + Multer being quite convenient.
try this :
router.post("/", upload.single("formfile"), (req, res) => {
console.log(req.formfile + " and exit.");
});
i think the headers should be:
{"Content-Type": "multipart/form-data"}
instead of application/json.
This is my app.js file:
var express = require('express');
var app = express();
var path = require('path');
var $ = require('jquery');
var nodemailer = require('nodemailer');
app.use('/static', express.static(path.join(__dirname, 'static')));
app.get('/', function(req, res) {
res.sendFile('./views/index.html', {"root": __dirname});
});
app.post('/contact/', function(req, res){
console.log(req.body);
});
and my post request from another file, which is called when a form is submitted:
$('form').submit(function(e){
e.preventDefault();
var content = $('#message').val();
var email = $('#EmailInput').val();
var reason = $('#reason').val();
$.post('/contact', { 'content': content, 'email': email, 'reason': reason }, function(data){
console.log(data);
});
})
However, whenever the form is submitted, the post request is successful, it's just no data has been passed.
req and req.body both return undefined. I can't figure out why.
you need the body parser to populate the body property of the request object
npm install body-parser
then include
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
documentation for your particular use case and tweaking may be found here
edit: be sure to include this BEFORE your route handlers are declared