Using bodyParser for solution to Payload Too Large - reactjs

Novice here. I am trying to send a photo within a rich-text editor to the API but receive the 413-payload too large error. I've read that the solution to this is to use a body-parser but once I try that it messes up all my routing. Since I'm a novice and used YouTube tutorials to put the routing together I'm not exactly sure how to fix it with the body-parser.
I'm proxying API Requests using "proxy": "http://localhost:8800/api/ in the package.json and using express' app.use with axios to post/get data from mysql database. For example:
const app = express()
app.use(express.json())
app.use("/api/posts", postRoutes)
const router = express.Router()
router.get("/", getPosts)
export const getPosts = (req, res)=>{
const q = req.query.cat ? "SELECT * FROM posts WHERE cat=?" : "SELECT * FROM posts"
db.query(q, [req.query.cat], (err, data) =>{
if(err) return res.status(500).send(err);
return res.status(200).json(data);
}
)
}
I tried using body-parser
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
but I get the error
Proxy error: Could not proxy request /posts from localhost:3001 to http://localhost:8800/api (ECONNRESET).
Any help or direction will be must appreciated.

Related

Adding an http redirect to a secure application in React.js

I have built a react.js application running on https. I would like to arrange it so that if the user goes to the non-secure (http) version of the url it gets redirected to https instead of just a not found error.
Heres the code I have now:
var https = require("https");
https.createServer(httpsOptions, expressApp)
.listen(middle_port);
const { createServer } = require("https");
const handle = app.getRequestHandler();
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(gui_port, (err) => {
if (err) throw err;
console.log("Gui listening on " + gui_port);
});
Whilst it is possible to do it via React, I would highly suggest you do this at the server level via Nginx or something and add the redirect rules there. If however you still want to do it via React, check out react-https-redirect

Prerender.io with reactjs/express application not recognizing Prerender token

I'm trying to get prerender set up with my application. I'm using react on the client side, and express on the server side. I set up an account on prerender IO, and have installed the prerender-node middleware as recommended by the site. Here is what my server looks like:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const SocketManager = require('./sockets/SocketManager')
const path = require('path');
const users = require("./routes/api/users");
const queries = require('./routes/api/queries');
const forumActions = require('./routes/api/forumActions');
// Routes
app.use("/api/users", users);
app.use("/api/queries", queries);
app.use("/api/forumActions", forumActions);
// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
app.use(require('prerender-node').set('prerenderToken', 'xxxTOKEN_CODExxx'));
const port = process.env.PORT || 80;
const server = app.listen(port, () => console.log(`Server running on port ${port} !`));
const io = require('socket.io')(server);
io.on('connection', SocketManager);
On the client side I'm using react-helmet to dynamically render the meta tags (title, description, etc.) based on the route. Ideally I would like to be able to share posts on social media and have the meta data display (which to my understanding prerender can do by prerendering pages specifically for web crawlers).
I've set up a prerender.io account and added my URL to the cached pages, but for some reason I am getting a message saying "We haven't seen a request with your Prerender token yet.". I am hosting on heroku, and have tried adding the token using the heroku CLI, which still hasn't fixed the issue.
Is there a step I'm missing, or did I not set this up correctly? Thanks!
It looks like you might need to move the prerender-node middleware higher up in your file so that it executes just after your routes but before the index file is served back.
Then you can change your user agent in your browser to Googlebot and visit your URL. If the middleware is set up properly, you would see a prerendered response and a request in your Prerender.io Crawl Stats.

AXIOS CORS PROBLEM. Server has "Access-Control-Allow-Origin: *" but Axios can't see it. why?

I have a CORS problem with axios.
The server is fine, I am sending Access-Control-Allow-Origin: * on all routes.
I can even login using the same backend, but for some reason logout is not working, axios can't see the headers.
I made a video:
https://youtu.be/vHfyk8BteLA
Can somebody explain that? When I check the network with a GET on the browser the header is there, but when the get is triggered by axios the header vanishes.
logout = () => {
const token = window.localStorage.getItem('jwt_access_token');
const request = axios.post('https://localhost/vintiapi/public/api/logout?token='+token);
this.setSession(null);
request.then(response => {
console.log('logout');
});
};
The error message suggests that it's the preflight request that's not getting the header. If you're using the cors module, you'll need to handle the OPTIONS request yourself:
// From: https://expressjs.com/en/resources/middleware/cors.html#enabling-cors-pre-flight
var express = require('express')
var cors = require('cors')
var app = express()
app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
Or you can enable it for all preflight requests:
app.options('*', cors())

expressJWT blocking public folder, how to unblock?

my express/node backend app and frontend app used to be separated, the backend run on localhost:3000 and the front end app was started with ng serve and run on localhost:4200
However after I builded the app, and all the frontend stuff got minified and put in /public/ folder, they both run on port 3000. I'm pretty sure they are supposed to work like that. Since i'm using expressJWT middleware to protect some of my routes for visitors without a token, i'm now getting unauthorized 401 when trying to receive the frontend app in the browser.....
As the image shows, i can aparently load the index.html without problems, i can also load all the external hosted sources like boots strap and jquery etc...
but my own .js files is 401. I think it is because of the expressJWT, but i'm not entirely sure. Does anyone know what the problem is and how to solve it ?
It could also be express that is wrong configured?
as you can see i have tried to "ubnlock" the public folder like so:
app.use(expressJWT({secret: secret}).unless({path :
['/','../public/*','/api/authenticate', '/api/register']}))
full express:
const express = require("express")
const bodyParser = require("body-parser")
const logger = require('morgan')
const api = require("./api/api")
const path = require('path')
const secret = require('./models/secrets')
const expressJWT = require('express-jwt')
const cors = require('cors');
const app = express()
app.set("json spaces", 2)
app.use(logger("dev"))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// CORS middleware
app.use(cors());
app.use(expressJWT({secret: secret}).unless({path : ['/','../public/*','/api/authenticate', '/api/register']}))
app.use("/api/", api)
app.get('*', (req,res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
app.use(function (req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})
app.use(function (err, req, res, next) {
console.error(err.status)
res.status(err.status || 500)
res.json({ msg: err.message, status: err.status })
})
// Body Parser middleware
app.use(bodyParser.json());
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
//Call this to initialize mongoose
function initMongoose(dbConnection) {
require("./db/mongooseConnect")(dbConnection)
}
app.initMongoose = initMongoose
module.exports = app
use express static middleware before using jwt.
example:
app
.use(express.static(STATIC_PATH))
.use(
exjwt({ secret: SECRET }).unless({
path: [/\/api\/v1\/identify/]
})
)
I am not 100% sure but I guess you have problem with this line.
app.use(expressJWT({secret: secret}).unless({path : ['/','../public/*','/api/authenticate', '/api/register']}))
app.use("/api/", api)`
Try this. putting single / should solve.
app.use('/api',expressJwt({secret: secret}).unless({path: ['/','/public/*','/api/authenticate', '/api/register']});

Receiving "Cannot GET /" error when trying to connect using Node.js/Express

Recently I started trying to get into Node.js/React and am using this tutorial https://auth0.com/blog/build-a-chat-app-with-react/.
However, even though I have followed the steps, I seem to be encountering an error. My page is displayed as "Cannot GET /" after hitting yarn start. I've found answers here NodeJS w/Express Error: Cannot GET /
and here "Cannot GET /" with Connect on Node.js
Neither of these made sense to me though, as my code seems to differ from theirs slightly. I understand that the page doesnt know where to look for my GET request, and therefore what information to pull, but im not sure how to fix it.
The code in question, GET request at the end. Thanks.
// server.js
const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const app = express();
const Pusher = require('pusher');
//initialize Pusher with your appId, key and secret
const pusher = new Pusher({
appId: 'APP_ID',
key: 'APP_KEY',
secret: 'SECRET',
cluster: 'YOUR CLUSTER',
encrypted: true
});
// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// API route which the chat messages will be sent to
app.post('/message/send', (req, res) => {
// 'private' is prefixed to indicate that this is a private channel
pusher.trigger( 'private-reactchat', 'messages', {
message: req.body.message,
username: req.body.username
});
res.sendStatus(200);
});
// API route used by Pusher as a way of authenticating users
app.post('/pusher/auth', (req, res) => {
const socketId = req.body.socket_id;
const channel = req.body.channel_name;
const auth = pusher.authenticate(socketId, channel);
res.send(auth);
});
// Set port to be used by Node.js
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function(req, res) {
console.log('Node app is running on port', app.get('port'));
});
I assume that you are sending get request to localhost:5000 which isn't defined in your server so it can't send response back, because you are using react you want to send request on port on which react is running(3000 by default) so try accessing using localhost:3000 and it should work.
You need to have the route available in the code. Try reading up on Express Basic Routing
Try the below and take it from there. I'm assuming that you're running on port 5000, if not, point to whatever port is set in process.env.PORT
app.get('/', function (req, res) {
res.send('hello world');
})

Resources