How can I proxy form data using http-proxy-middleware? - node.js

I created a proxy on firebase using http-proxy-middleware.
It works on GET requests but does not pass the data I send via body in POST requests. I did some research and added the "onProxyReq" method to the options. This way it works when I send json body, but not when I send form data.
const functions = require("firebase-functions");
const express = require("express");
var bodyParser = require("body-parser");
const {
createProxyMiddleware,
fixRequestBody,
} = require("http-proxy-middleware");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var restream = function (proxyReq, req, res, options) {
if (req.body) {
let bodyData = JSON.stringify(req.body);
proxyReq.setHeader("Content-Type", "application/json");
proxyReq.setHeader("Content-Length", Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
};
app.use(
"/",
createProxyMiddleware({
target: "http://IPADDRESS:8080/api",
changeOrigin: true,
onProxyReq: restream,
bodyParser: false,
})
);
exports.api = functions.https.onRequest(app);
This code works with json body.
Changing "application/json" to "multipart/form-data" doesn't work.
All I want is to redirect the JWT token in the header and the FormData in the body.
What should be the best way for this?

Related

req.cookies is null and I don't know why

I've looked at a few previous stack overflow posts but can't figure out why this is happening.
I have included cookie parser before all my routes and the cookie is in the browser. For some reason I just can't access it.
const cookieParser = require("cookie-parser");
const cors = require("cors");
const AppError = require("./utils/appError");
const globalErrorHandler = require("./controllers/errorController");
const dishRouter = require("./routes/dishRoutes");
const userRouter = require("./routes/userRoutes");
const orderRouter = require("./routes/orderRoutes");
const imageRouter = require("./routes/imageRouter");
const app = express();
app.use(cookieParser());
app.enable("trust proxy");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.options("*", cors());
ROUTES...
Here is how I am accessing the req.cookies
First I do an axios call
axios({
method: "patch",
url: `http://localhost:8080/api/v1/users/me`,
data: this.state,
})
Then it goes through this middleware
router
.route("/me")
.patch(authController.protect, userController.updateProfile)
In authController.protect I do the following
try {
//1) Getting token and check if it exists.
let token;
if (
//POSTMAN
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
} else if (req.cookies.jwt) {
token = req.cookies.jwt;
}
console.log(`TOKEN: ${token}`);
console.log(req.cookies);
The console.log right above gives null.
I faced a similar issue with my code where I was getting null when checking req.cookies. I used express for my node.js files and I followed the explanations from the following links:
http://expressjs.com/en/resources/middleware/cors.html
https://developers.google.com/web/updates/2015/03/introduction-to-fetch
So from server side I added configuration to cors() and set credentials: true and on client side from my fetch() request I added credentials: 'include' and this gave me access to the cookies on my browser. My fetch() request was making use of the PUT method.

request body is empty in post method node js server

Login.js - react component.
I printed the JSON.stringify(credentials) object and it is valid but when i print the req.body in the server it is empty.
//sending a post request to the server with the username and password inserted by the user.
async function loginUser(credentials) {
console.log(JSON.stringify(credentials));
return fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(response => {
console.log(response);
})
};
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
you have to use a middleware to parse the json body in the post request,
you have not used bodyParser.json() as middleware
below is your updated code
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }));
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})

Express - `req.body` is always empty

I am trying to build a full stack(MERN) application. When I'm sending a request to my Express server with a JSON, I always see my req.body is empty. I can nowhere see my JSON inside my request.
I have tried using only app.use(bodyParser.json()) and app.use(bodyParser.urlencoded({ extended: true }));,but no change.
index.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
console.log("App");
require("./schema/data");
require("./routes/home_routes")(app);
require("./routes/table_routes")(app);
require("./routes/utility_routes")(app);
utility_routes.js
const mongoose = require("mongoose");
const Data = mongoose.model("data");
module.exports = app => {
app.get("/api/search_member", (req, res) => {
console.log("Utility", req);
console.log("Req Done");
// const search = await Data.findById({ member_id: req.body.member_id });
// console.log(search);
});
};
request.body
[0] body: {},
[0] route:
[0] Route {
[0] path: '/api/search_member',
[0] stack: [ [Layer] ],
[0] methods: { get: true } } }
request from client
onSearch = async value => {
console.log(value);
if (value) {
const searchData = await axios.get("/api/search_member", { value });
console.log(searchData);
}
};
You are making a GET request. GET request do not send body. To get req.body, make POST request to server.
Firstly:-
const searchData = await axios.post("/api/search_member", { value });
And Secondly,
app.POST("/api/search_member", async (req, res) => {
console.log("Utility", req);
console.log("Req Done");
});
This is what I use to accept the json
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.json());
app.use(cookieParser());
And in the request set headers like this.
Content-Type : application/json
Both the axios and http libraries from angular works with this settings for me.

ExpressJs request body is empty

I have an express app at localhost:5000 and a react app at localhost:3000.
I am calling it via
fetch(`${backendUrl}/charge`, {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/json"
},
body: {
stripeToken: token,
chargeAmount: this.state.donationAmount
}
})
And responding with
function route(req, res) {
console.log(req.body);
}
Server should be properly configured to work with CORS, but the body is still empty.
//configure env variables
require("dotenv").config();
//import packages
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");
//import route functions
const StripeRoute = require("./StripeRoute");
//setup app
const app = express();
const port = process.env.PORT || 5000;
//setup bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Setup CORS
app.use(cors());
app.options("*", cors()); // include before other routes
//Connect functions to API routes
app.post("/charge", StripeRoute);
module.exports = app;
According to the documentation, the body option should be one of a few specific types, Object not being one of them.
Try using a JSON string:
body: JSON.stringify({
stripeToken: token,
chargeAmount: this.state.donationAmount
})
EDIT: because you're using no-cors, you can't set Content-Type application/json. Instead, you need to generate a URL-encoded string and set Content-Type to application/x-www-form-urlencoded (because no-cors will only work using "simple headers", as explained here and further).

Nodejs bodyparser returning undefined for body variables

I'm trying to extract POST data using a NodeJS script (with Express). The body is received, but I cannot seem to extract the variable from it when posting to the page with Postman. The variable is undefined, although I have used the same code I found in different questions. I have correctly installed Nodejs, express and body-parser.
To clarify, I'm posting form-data with Postman with key 'username' and value 'test'.
Anyone knows what I'm doing wrong?
var https = require('https');
var fs = require('fs');
var app = require('express')();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var httpsOptions = {
key: fs.readFileSync('/home/privkey.pem'),
cert: fs.readFileSync('/home/cert.pem'),
};
var server = https.createServer(httpsOptions, app);
server.listen(3000);
app.get('/', function(req, res) { //On get
res.send(req.method);
});
app.post('/', function(req, res) { //On post
res.send( req.body.username );
});
I guess it has to do with the encoding:
JSON:
you have to set a header with Content-Type: application/json and
add the encoding in express before the route :
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Otherwise you can just use the option x-www-form-urlencoded and set the inputs

Resources