Get POST request body with express and fetch - javascript

I'm new to server-side development.
I'm trying to set up a node.js server that can receive posts.
My client-server code sends the post request:
function post(){
fetch('/clicked', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Text'})
})
.then(function(response){
if(response.ok){
console.log('POST success.');
return;
}
throw new Error('POST failed.');
})
.catch(function(error){
console.log(error);
});
}
And my Node.js server receives it:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/clicked', (req, res) => {
console.log(req.a);
console.log(req.b);
console.log(req.body);
res.sendStatus(201);
})
However, my server console logs all undefined.
What should I do to receive my POST request body?

Try setting up express.json() inside the app:
const express = require('express');
const app = express();
app.use(express.json())
app.post('/clicked', (req, res) => {
console.log(req.a);
console.log(req.b);
console.log(req.body);
res.sendStatus(201);
});

Add this before handling post request.
app.use(require('body-parser').json());
What body-parser does is, it will add all the information we pass to the API to the 'request.body' object.

Related

My app post data into JSON however it also throws this error "http://localhost:5000/write net::ERR_CONNECTION_RESET"

Sorry if I don't post the correct details, this is my first hands-on project after going through online tutorials.
I'm using React, node with axios to build a web app that captures status(available, in a meeting, lunch etc) and the time spent on each status.
The app works fine, it captures and writes the data onto the backend(JSON) however, I keep getting this error on the console.
POST https://localhost:5000/write net::ERR_CONNECTION_RESET
Uncaught (in promise) ERROR: Network Error
I've tried to look for a solution but can't find one that is similar to the tech-stack I used. Also, my lack of sufficient knowledge don't help either.
Any lead or read or solution will help.
pasting my code below:
My frontend code to push data into JSON file
const saveJson = (posts) => {
//api URL //end point from node server / express server
const url = "http://localhost:5000/write";
axios.post(url, posts).then((response) => {
//console.log(response);
}); };
The server.js code
const express = require("express");
const bodyParser = require("body-parser");
//calling packages
const fs = require("fs");
const morgan = require("morgan");
const cors = require("cors");
//Declare app
const app = express();
const port = 5000;
//middlewares
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(cors());
//default route for server
app.get("/", (req, res) =>
res.status(200).send({
message: "Server is running...",
})
);
const WriteTextToFileAsync = async (contentToWrite) => {
fs.writeFile("./src/data.json", contentToWrite, (err) => {
console.log(contenToWrite);
if (err) {
console.log(err);
} else {
console.log("Done writing to file...");
// res.json({ msg: "success" });
}
});
};
//Declare timerow/write route to accept incoming require with data
app.post("/write", async (req, res, next) => {
//take the body from incoming requestby using req.body and conver it into string
const requestContent = JSON.stringify(req.body);
await WriteTextToFileAsync(requestContent);
});
//404 route for server
app.use((req, res, next) =>
res.status(404).send({
message: "Could not find specified route requested...!",
})
);
//run server
app.listen(port, () => {
console.log(
`!!! server is running
!!! Listening for incoming requests on port ${port}
!!! http://localhost:5000
`
);
});

Sending data from Javascript to Node.js

I am trying to create a very basic function,
suppose my javascript data is
const data = 1234;
how do i send this data to a node server i created using express framework
const express = require("express");
const app = new express();
app.get("/", (req, res) => {
res.send("home");
});
app.post("/datastream", function (req, res) {
res.send('You sent the data: "' + req.body.data + '".');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`server started on port ${PORT}`));
If you want to send it from browser and your server is running locally:
const data = 1234
fetch('http://localhost:5000/datastream', {
method: 'POST',
body: JSON.stringify({ data }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.text())
.then(data => console.log(data))
.catch(err => console.log(err))
Now you need to install body-parser middleware to be able to deserialize your JSON data npm install body-parser and attach it to your app. Add this to your server code:
const bodyParser = require('body-parser')
// ...
app.use(bodyParser.json())
If everything went good (your server is running on specified port) then it should log You sent the data: 1234. after you run your browser code
You can send data from client to server using fetch method (very basic example):
const data = 1234;
fetch('/datastream', {
method:"POST",
body: JSON.stringify({data: data})
}).then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
})
.catch(function(err) {
console.log('Fetch Error :' + err);
});

Making a set by express server cookie be visible to client

I am new to Express and I have problems with sending cookies.
I made a simple express app that needs to set a cookie to the browser. This is the server:
const express = require('express');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const app = express();
//app.use(cors());
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['http://127.0.0.1:5500']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
res.append('Access-Control-Allow-Credentials', 'true');
next();
});
app.use(cookieParser());
app.use(express.json());
const PORT = 9000;
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.cookie('testCookie', 'random value', {httpOnly: false, secure: false});
res.send({user: "test", password: "test123"});
})
app.listen(PORT, console.log(`Server started on port ${PORT}`));
So it successfully sends to the browser the testCookie on request with fetch:
let response = await fetch('http://localhost:9000/', {
method: 'GET',
mode: 'cors',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.json());
console.log(response);
After the request the cookie is successfully send because is in the Chrome cookie tab but document.cookie returns an empty string. And also when i make request to a page the request doesnt contains the Cookie header.
How can I make the cookie to be visible to document.cookie and also to the browser to send his Cookie header?
I strongly suggest you to use an npm package: jsonwebtoken, https://www.npmjs.com/package/jsonwebtoken
This way it's much cleaner:
const jwt = require ('jsonwebtoken');
// Create login logic here (check password etc.);
const token = jwt.sign(user, secret, expiration);
res.status(201).json({
status: 'success',
token
});
Try using JSON format instead of res.send since you have a body parser in place already and it's a best practice in modern APIs.

'body' not accessible in Express router post request

I'm using Express router functions to handle some POST requests.
Client.js
let data = {
endpoint: "Blah Blah";
};
return fetch('/api/get-preferences/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
Server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
class HTTPServer {
constructor(credentials, app) {
this.app = app;
this.specifyRoutes();
}
specifyRoutes() {
this.router = express.Router();
this.router.use((req, res, next) => this.jwtVerify(req, res, next));
this.app.use('/api', this.router);
this.router.post('/get-preferences', this.getPref);
}
jwtVerify(req, res, next) {
console.log(req.body); // This prints "undefined".
next();
}
}
I can't access the data that I sent from the client side on the server side in the jwtVerify function and once this is fixed, I would like to pass that data to the getPref function in the /get-preferences route.
Two issues here. First, update:
this.app.use(bodyParser.json());
Second:
this.app.use('/api', this.router);

Node - Post request showing undefined

Im making a angular2/Node.js application. Right now when i try to get a object from the node server, it returns just fine. However, when i try to post data to the node server. The request.body shows undefined. What am i doing wrong ?
server.js
// Test
router.get('/test', function (req, res) {
res.json({test:true}); // Works
});
// Post
router.post('/rest', function (req, res) {
var body = req.body;
console.log(body); // Undefined
res.json({test:true});
});
app.ts
constructor(private http:Http){
console.log("Test")
http.get('/api/User/test').subscribe(result => {
console.log(result.json());
});
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post('/api/User/rest',{test:'Testing req'},{headers:headers})
.subscribe(result => {
console.log(result.json());
});
}
Did you install body-parser?
npm install body-parser --save
and before your routes, add it to your express application
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
see also: https://github.com/expressjs/body-parser

Categories

Resources