S3FS Node and Express, s3fsImpl is not defined - node.js

I am trying to put a file into a s3 bucket from my node server using a post request in node.js. Here is the part of my node server that sets up the routes.
// Get Dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get API Routes
const api = require('./server/routes/api');
const app = express();
// Parse for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// post static path to dist
app.use(express.static(path.join(__dirname,'dist')));
// Set our api routes
app.use('/api', api);
Here is api.js
const express = require('express');
const router = express.Router();
var fs = require('fs');
var S3FS = require('s3fs');
var s3fsImp1 = new S3FS('bucketname',{
accessKeyId: 'xxxxxxxxx',
secretAccessKey: 'xxxxxxxxxxxx'
});
router.get('/',(req,res) => {
res.status(200).json({ message: 'Connected!' });
});
router.post('/upload',(req,res) => {
var file = req.body.file;
console.log(file);
var stream = fs.createReadStream(file)
return s3fsImpl.writeFile(file,stream).then(function(){
fs.unlink(file,function(err){
if(err)
console.error(err);
});
res.send('done');
}).catch(function (err) {
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
});
});
module.exports = router;
Node throws the error ReferenceError: s3fsImpl is not defined when I call that post method from postman. Any help would be appreciated.

Related

Getting an undefined token of add category in console

I am new to React and Node and I'm getting an undefined token in console when I add category I get undefined in the console. I am using cookie-parser.
server.js file:
const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const cookieParser = require('cookie-parser')
const connectDB = require('./database/db');
const authRoutes = require('./routes/auth');
const categoryRoutes = require('./routes/category');
//middleware
app.use(cors());
//dev specifies it is for development
app.use(morgan('dev'));
//express.json allows us to parse incoming request in json in the format of a json
app.use(express.json());
app.use(cookieParser());
app.use('/api/auth', authRoutes);
//route for category
app.use('/api/category', categoryRoutes);
connectDB();
app.get('/', (req,res) => {
res.send('Inside Server');
});
const port = process.env.PORT || 5000;
app.listen(port, ()=>console.log(`Listening on port ${port}`));
category.js (controller file)
exports.create = (req,res) => {
setTimeout(()=> {
res.json({
successMessage: `${req.body.category} was created!`
});
}, 5000);
};
category.js (routes file)
const express = require('express');
const router = express.Router();
const categoryController = require('../controllers/category');
const { authenticateJWT } = require('../middleware/authenticator');
router.post('/', authenticateJWT , categoryController.create);
module.exports = router;
authenticator.js (middleware file)
const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../config/keys');
exports.authenticateJWT = (req, res, next) => {
const token = req.cookies.token;
console.log(token);
}
keys.js file
//it is gonna tell us/ signifying if we are live if in develoopment or in production
const LIVE = false;
if (LIVE) {
module.exports = require('./prod.js');
} else {
module.exports = require('./dev.js');
}
Console screen:
Instead of undefined i should be getting token.
Any help will be highly appreciated.
Thanks!
Is there a token Cookie available? (You can check using the inspector of your browser, normally in the „application“ tab. If you are sending the request using any tools like postman, curl, wget, …, you have to set the cookie first.)
Was the cookie available on any other routes? What’s the difference between these routes and the category route? Is it possible that your cookie is constrained to a specific path, e.g. to /api/auth? If so, adjust the path in res.cookie.

Express API is not getting called from react.js

Hi everyone facing issue for API not getting called from node(express.js).
When i call it using controller file it returns status 200 with data=[] empty array and does not print in console ' [] ' but when i call the same API in the product.js(API file) it gets called
gives response as status 200 and data=hi
i have disabled app.disable("etag"); in app.js
Calling Api from react.js to Express.js API
export const getRandomProductAPI = () => Axios.get(`${url}/v1/product/getRandomProduct`);
I am having API folder in which i am reciving the request from react.js in Product.js(API file).
const express = require("express");
const router = express.Router();
const multer = require("multer");
const productController = require("../controllers/ProductController");
const storage = multer.memoryStorage({
destination: function (req, file, callBack) {
callBack(null, "");
},
});
const uploadProduct = multer({ storage }).single("productImage");
const updateProduct = multer({ storage }).single("newEditImage");
// router.get("/getRandomProduct", (req, res) => {
// res.status(200).send("hi");
// });
router.post("/add", uploadProduct, productController.addProduct);
router.get("/:category", productController.getProduct);
router.delete("/:id/:imageName", productController.deleteProduct);
router.patch("/", updateProduct, productController.updateProduct);
router.get("/Id", productController.getLatestProductId);
router.get("/getRandomProduct", productController.getRandomProduct);
module.exports = router;
API which is got called is the last one-> router.get("/getRandomProduct",roductController.getRandomProduct);
Controller Code ProductController.js
const getRandomProduct = async (req, res) => {
console.log("called");
res.status(200).send("hi");
};
module.exports = {
addProduct,
getProduct,
deleteProduct,
updateProduct,
getLatestProductId,
getRandomProduct,
};
App.js code
const express = require("express");
const morgan = require("morgan");
const helmet = require("helmet");
const cors = require("cors");
const path = require("path");
require("dotenv").config();
const middlewares = require("./middlewares");
const api = require("./api");
const app = express();
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client/build")));
}
app.use(morgan("dev"));
app.use(helmet());
app.use(cors());
app.use(express.json());
// app.disable("etag");
app.get("/", (req, res) => {
res.json({
message: "🌎🌍🌏 Furnitures ",
});
});
app.use("/v1", api);
app.use(middlewares.notFound);
app.use(middlewares.errorHandler);
module.exports = app;

form-data in node not showing

I have a node express set up.
While using Postman, Iam able to see data sent through x-www-form-urlencoded but the same is not being shown through form-data.
below are the codes
Server.js
const express = require('express')
var cors = require('cors')
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var cookieParser = require('cookie-parser')
app.use(cookieParser())
app.use(cors())
const index = require("./routes/index")
app.use("/", index)
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() { console.log(`Running on ${port}`) });
Index.js
const express = require('express')
const router = express.Router()
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const func = require('./functions')
const time = new Date().toISOString().slice(0, 19).replace('T', ' ')
const nodemailer = require("nodemailer");
router.use('/auth', require('./auth')
Auth .js
const express = require('express')
const router = express.Router();
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const nodemailer = require("nodemailer");
const func = require('./functions')
router.post('/register', asyncMiddleware( async(req, res, next) => {
res.send({ success: true, message: req.body })
}))
You should use Multer to handle form-data.
Multer is a node.js middleware for handling multipart/form-data
body-parser middleware can't handle multipart/form-data.
This does not handle multipart bodies, due to their complex and typically large nature.
In case you need to handle a text-only multipart form, you should use the .none() method:
E.g.
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const app = express();
app.use(upload.none());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/auth/register', (req, res) => {
res.send({ success: true, message: req.body });
});
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() {
console.log(`Running on ${port}`);
});
postman:

POST route indicating 404 error (EXPRESS)

Getting a 404 error on my POST route, here is what I have done in my auth.js (routes) file:
const express = require('express');
const router = express.Router();
const connection = require('../../helpers/db.js');
const bodyParser = require("body-parser");
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({
extended: true
}));
//create a new user
router.post('/signup', function (req, res) {
const insert = `INSERT INTO users ( email, password, name, lastname) values ('${req.body.email}', '${req.body.password}','${req.body.name}', '${req.body.lastname}' )`
connection.query(insert, function (err, result) {
if(err) {
console.log('mysql error', error);
res.status(500);
res.send(error);
} else {
console.log('a new user was added!');
res.send('Congrats, new user!');
}
})
});
module.exports = router;
Here is my app.js file:
const http = require("http");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const app = express();
const authRouter = require("./routes/auth/auth");
// Configuring the app
app.use(morgan("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public"));
app.use("/signup", authRouter);
//starting node server
const server = app.listen(process.env.PORT || 3001, function(err) {
if(err) throw err;
console.log("Listening on port " + server.address().port);
});
If I change my route into a GET, it works fine, but as soon as I do a POST route it would keep telling me on postman there is a 404 error, been trying many things but im now stuck! Im a beginner here :)
I think you added a prefix to your route so the route is /signup/signup
Try to change this
app.use("/signup", authRouter);
To this
app.use(authRouter);

Testing failed with Mocha, Chai and Supertest (NodeJS), retrieving data from mongodb

It is my first time testing the routes in node js and I'm using mocha, supertest and chai. Here is my server.js file:
const express = require('express');
const app = express();
const path = require('path');
const http = require('http').Server(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const fs = require('fs');
//const helpers = require('./includes/helpers.js');
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../dist/chat/')));
require('./listen.js')(http);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS");
next();
});
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
MongoClient.connect(url, { poolSize: 10 }, function (err, client) {
if (err) { return console.log(err) }
const dbName = 'testdb';
const db = client.db(dbName);
require('./routes/create.js')(app, db);
require('./routes/remove.js')(app, db);
require('./routes/update.js')(app, db);
require('./routes/read.js')(app, db);
require('./routes/add.js')(app, db);
require('./routes/auth.js')(app, db);
require('./routes/search.js')(app, db);
});
And i want to test the read.js route, basically the read route returns a JSON array which has a few key/value parameters e.g. id (key), name (key) etc.
this is my test.js file:
var assert = require('assert');
const express = require('express');
const app = express();
var read = require('../server/routes/read.js');
var http = require('http');
var helpers = require('./include/helpers');
//var api = require('../server/server.js');
var should = require('chai').should();
var expect = require('chai').expect;
var supertest = require('supertest');
var api = supertest('http://localhost:3000');
var request = require('supertest');
describe('The read route',()=>{
it('should be an object with valid parameters',function(done){
api.get('/api/read')
.set('Accept','application/json')
.expect(200)
.end(function(err,res){
if (err) throw err;
expect(res.body).to.not.equal(null);
expect(res.body).to.have.property('id');
done();
});
});
});
The testing works fine, the only issue is that when i run the line: 'expect(res.body).to.have.property('id')' , the test fails saying that expected [], i dont get it whats wrong, my read route returns a JSON array with parameters: {id:4,prodname:'iPhone',type'phone',description:'Nice phone'} (BTW it is returning data from mongodb)
it should detect the id inside the parameter. Any help?

Resources