Empty body Api rest express node js - javascript

I'm trying to make an API using express in nodejs.
This api should get a request with a photo and post that photo to firebase storage.
The main problem is that for some reason the body of the requests I send are empty.
This is the code for the server:
const express = require("express");
const morgan = require("morgan")
const cors = require('cors')
const app = express();
// Settings
app.set('port', process.env.PORT || 3000)
app.set('json spaces', 4)
// middleware
app.use(morgan("dev"))
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(cors({origin: "http://localhost:3001"}))
// routes
app.use(require("./routes/index"))
app.listen(app.get('port'), () => {
console.log("Server using port " + app.get('port'));
});
Routes
const { Router } = require('express')
const router = Router()
router.post('/postImage', async (req, res) => {
try {
const image = req.body
console.log(image) // Here I only get an epty object "{}"
return res.status(200).json(image)
}
catch(error) {
console.log(error)
return res.status(500).json({error})
}
})
module.exports = router
Client side
const postImage = async (image) => {
console.log(image) // Here I get the image data
const response = await fetch("http://localhost:3000/postImage", {
method: "POST",
body: {message: "image"}
})
const data = await response.json()
}
I've tried using body-parser but it seems to be deprecated

you have to send an image from the front end in formData.
const data = new FormData();
data.append('myFile', 'Image Upload');
In back end use multer to upload file to server.
first install multer by : npm i multer
const multer = require("multer");
//Configuration for Multer
const upload = multer({ dest: "public/files" });
app.post("/api/uploadFile", upload.single("myFile"), (req, res) => {
// Stuff to be added later
console.log(req.file);
});
Here is a proper Guide to upload file using multer express js

Related

How can I save an image on the server as a URL?

EDIT
I removed app.use(fileUpload());. So it finally worked.
But unfortunately in the folder images of the backend I only get these files c43jnfeh734hdfudf.
For this reason, nothing is displayed in the frontend.
const imagePath = req.file.path
const description = req.file.originalname
console.log(imagePath)
console.log(description)
images\c43jnfeh734hdfudf
empty
I have a problem. I would like to save images with a fixed URL on my server.
I found the following code snippet, but unfortunately it doesn't work.
I get the following error in the backend: 'TypeError: Cannot read property 'path' of undefined'.
The following values are 'undefined'. const imagePath = req.file.path const description = req.body.description
How can I save an image as a URL on the server?
Here is the tutorial, where I found the code snippet https://github.com/meech-ward/sammeechward.com_mdx/blob/master/content/articles/uploading-images-express-and-react/index.mdx
React
import { useState } from 'react'
import axios from 'axios'
export default function App() {
const [file, setFile] = useState()
const [description, setDescription] = useState("")
const [image, setImage] = useState()
const submit = async event => {
event.preventDefault()
const formData = new FormData()
formData.append("image", file)
formData.append("description", description)
const result = await axios.post('/api/images', formData, { headers: {'Content-Type': 'multipart/form-data'}})
setImage(result.data.imagePath)
}
return (
<div className="App">
<form onSubmit={submit}>
<input
filename={file}
onChange={e => setFile(e.target.files[0])}
type="file"
accept="image/*"
></input>
<input
onChange={e => setDescription(e.target.value)}
type="text"
></input>
<button type="submit">Submit</button>
</form>
{ image && <img src={image}/>}
</div>
)
}
Backend
const express = require('express')
const fs = require('fs')
const multer = require('multer')
const upload = multer({ dest: 'images/' })
const app = express()
// app.use('/images', express.static('images'))
app.get('/images/:imageName', (req, res) => {
// do a bunch of if statements to make sure the user is
// authorized to view this image, then
const imageName = req.params.imageName
const readStream = fs.createReadStream(`images/${imageName}`)
readStream.pipe(res)
})
app.post('/api/images', upload.single('image'), (req, res) => {
const imagePath = req.file.path
const description = req.body.description
// Save this data to a database probably
console.log(description, imagePath)
res.send({description, imagePath})
})
app.listen(8080, () => console.log("listening on port 8080"))
routes/Test.js
const express = require("express");
const router = express.Router();
module.exports = router;
const auth_util = require("../utilities/auth_util");
const pgclient = require("../app");
const multer = require('multer')
const upload = multer({ dest: 'images/' })
// app.use('/images', express.static('images'))
router.get('/images/:imageName', (req, res) => {
// do a bunch of if statements to make sure the user is
// authorized to view this image, then
const imageName = req.params.imageName
const readStream = fs.createReadStream(`images/${imageName}`)
readStream.pipe(res)
})
router.post('/api/images', upload.single('image'), (req, res) => {
console.log(req.file)
console.log(req.files)
const imagePath = req.file.path
const description = req.body.description
// Save this data to a database probably
console.log(description, imagePath)
res.send({ description, imagePath })
})
// added the lines below
const path = require("path");
router.use(express.static(path.join(__dirname, 'build')));
router.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.js
const express = require("express");
const cors = require("cors");
//const fileUpload = require("express-fileupload");
const session = require("express-session");
const { Pool } = require("pg");
const app = express();
app.use(express.json());
//app.use(fileUpload());
//------------------------------CORS settings------------------------------
var whitelist = [
"http://localhost:3000",
"http://localhost:3001",
];
var corsOptions = {
credentials: true,
exposedHeaders: ["set-cookie"],
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
// callback(null, true)
callback(new Error("Not allowed by CORS!!"));
}
},
};
app.options("*", cors(corsOptions));
const pgclient = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
module.exports = pgclient;
app.set("trust proxy", 1);
const testRoute = require("./routes/test");
app.use("/test", cors(corsOptions), testRoute);
app.get("/", cors(corsOptions), (req, res, next) => {
res.send("Welcome");
});
module.exports = app;
First of all, you need to remove express-fileupload. There is no need to use it alongside multer.
To have the correct file with an extension in specified folder, you need to change this part of your code:
remove this line:
const upload = multer({ dest: 'images/' })
change it to:
// routes/Test.js
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'images')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({ storage: storage })
For conventional and standard way to prevent overwriting the same file names, you need to change filename to this:
filename: function (req, file, cb) {
cb(null, `${Date.now()}-${file.originalname}`)
}
According to this answer, multer uses a kind of cookie in its file uploads and out of date versions of the cookie cause the file upload to fail. Try clearing your browser's cookies.
multer - req.file always undefined
Edit: here is the script working on my end with some images:
I did have to make one minor edit to get the example to work on chrome. To avoid the CORS policy, the front and back end must both be hosted at the same port. So, I added get route to statically serve the react page from the expressjs server:
const express = require('express')
const fs = require('fs')
const multer = require('multer')
const upload = multer({ dest: 'images/' })
const app = express()
// app.use('/images', express.static('images'))
app.get('/images/:imageName', (req, res) => {
// do a bunch of if statements to make sure the user is
// authorized to view this image, then
const imageName = req.params.imageName
const readStream = fs.createReadStream(`images/${imageName}`)
readStream.pipe(res)
})
app.post('/api/images', upload.single('image'), (req, res) => {
console.log(req.file)
console.log(req.files)
const imagePath = req.file.path
const description = req.body.description
// Save this data to a database probably
console.log(description, imagePath)
res.send({ description, imagePath })
})
// added the lines below
const path = require("path");
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(8080, () => console.log("listening on port 8080"))

NodeJS: Cookie is undefined

I'm trying to make a simple GET request to my localhost:8080.
When I make the GET request with Postman, I set a simple cookie. Now, in the main file, I've:
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());
const app_router = require('./routes/router');
app.use("/api", app_router);
app.use(express.static('public'));
app.listen(8080, function () {
console.log('Outdoor Localization GNSS middleware.');
});
In routes/router.js I have:
var express = require('express')
const router = express.Router();
const axios = require('axios');
const url = 'http://10.10.0.145:80/api'
router.use(express.json());
router.get('/*', function (request, response) {
console.log(request.Cookie)
axios
.get(request_url)
.then(res => {
console.log(request.Cookie)
})
.catch(error => {
console.error(error)
})
});
The problem is that request.Cookie always return undefined...why is this happening?
you should be accessing the property request.cookies instead of request.Cookie

req.body is empty, why?

I want to send some data to my MongoDB database, but in router.post my req.body is empty, if I use stuff that I put in my send function in User(req.body) instead of req.body data will be send to my MongoDB database correctly.
This is my router that I use, router.get work fine, it return database tables correctly on /api page:
const router = require("express").Router();
const User = require("./model/models");
const parser = require("body-parser").json();
router.get("/", async (req, res) => {
const data = await User.find({});
res.json(data);
});
router.post("/",parser,async (req, res) => {
console.log('1')
console.log(req.body)
console.log('2')
parser.v
await User(req.body).save();
res.json({"msg": "ok"});
});
module.exports = router
This is my index.js file code:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const parser = require("body-parser").json();
var path = require('path');
app.use(express.urlencoded(true));
app.use(express.json());
app.use(parser);
app.use('/',require("./routes/routes"))
app.use(express.static(__dirname +'/public'))
app.use("/api", require('./data/api'))
app.listen(5000,function(){
console.log('server is alive')
})
This is function that what I use to send data:
const btn1 = document.getElementById('btnEnter')
let Login = "123"
btn1.addEventListener('click' ,e=>{
send({newsTxT : "someTextHere",newsZag:"someZag",author:"SomeAuthor"})
})
const send = async(body) => {
let res = await fetch("/api", {
method: "post",
header: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(body)
});
let data = await res.json();
console.log(data)
}
The only weird thing I see is that you are using a json body-parser and also the express.json() both technically do the same, but body-parser is deprecated so it might be causing a bug.
Also you don't have to import it again in the routes, placing app.use(express.json()) at index.js will make it work for all endpoints/routes.
See how this refactor goes:
const router = require('express').Router()
const User = require('./model/models')
router.get('/', async (req, res) => {
const data = await User.find({})
res.json(data)
})
router.post('/', async (req, res) => {
console.log('1')
console.log(req.body)
console.log('2')
await User(req.body).save()
res.json({ 'msg': 'ok' })
})
module.exports = router
index.js
const express = require('express')
const app = express()
var path = require('path')
app.use(express.urlencoded(true))
app.use(express.json())
app.use('/', require('./routes/routes'))
app.use(express.static(__dirname + '/public'))
app.use('/api', require('./data/api'))
app.listen(5000, function () {
console.log('server is alive')
})
The following worked fine:
const express = require("express")
const app = express()
const router = express.Router()
router.use(express.json())
app.use(router)
router.post('/api/user', function(req, res) {
// ...
}
I see the difference may be using the: app.use(router)
Note that in the above code the statement:
router.use(express.json())
can be replaced with (using the body-parser):
const bodyParser = require('body-parser')
router.use(bodyParser.json())
This worked fine with express version 4.17.1, body-parser version 1.19.0 and NodeJS version 12.18.3

Respond to client after receiving client to server POST request (Node.JS)

I have been attempting to respond to a client-side request with Node.JS. I have discovered Node JS - call function on server from client javascript, which seems to explain what I want, except that I can't seem to translate it to my program.
Here is the request via POST in index.html:
$.post("/", {data: 'hi'}, function(result){
$("body").html(result);
});
what I was hoping it would do would be write the result of the call, from my server.js (Node):
const express = require('express');
const path = require('path');
const http = require('http');
const fs = require('fs');
function handler(data, app){
if(req.method == "POST"){
app.setHeader('Content-Type', 'text/html');
app.writeHead(200);
app.end(data);
}
}
const BUILDPATH = path.join(__dirname);
const { PORT = 3000 } = process.env;
const app = express();
app.set('port', PORT);
app.use(express.static(BUILDPATH));
app.get('/*', (req, res) => res.sendFile('static/index.html', { root: BUILDPATH }));
const httpServer = http.createServer(app);
httpServer.listen(PORT);
console.info(`🚀 Client Running on: http://localhost:${PORT}`);
try this code:
const express = require('express');
const path = require('path');
const http = require('http');
const fs = require('fs');
function handler(data, app){
if(req.method == "POST"){
app.setHeader('Content-Type', 'text/html');
app.writeHead(200);
app.end(data);
}
}
const BUILDPATH = path.join(__dirname);
const { PORT = 3000 } = process.env;
const app = express();
app.set('port', PORT);
app.use(express.static(BUILDPATH));
app.get('/', (req, res) => {
res
// best practice is to always return an status code
.status(200)
// just return an json object
.json({"msg": "ok, it all works just fine"})
});
const httpServer = http.createServer(app);
httpServer.listen(PORT);
console.info(`🚀 Client Running on: http://localhost:${PORT}`);
The issue is, is that the only route your Node server listens to is the one you define with /*. As you can see, that route returns your index.html file to the client. You did not specify a route that listens for a request that comes from the client.
To solve the issue, you will have to define a route that listens on a specific route for the request you are trying to make from your client.
I see you are using ExpressJS. here is the documentation on writing routes.

Node.js REST endpoint not catching parameters passed from axios request

I'm making a POST request from a React front-end using axios to an endpoint to save some data to my DB (MongoDB). I'm getting an error that one cannot read property 'name' of undefined. I think that's occurring because req.body is undefined but I can't understand what's wrong with my axios request. I logged all the parameters and they are there (not undefined). The axios request and the endpoint are written below. Any help will be appreciated. Thanks!
Axios Request
const uploadElement = async (name, HTMLCode, JSCode, CSSCode, screenshot) => {
console.log(name)
try {
await axios({
method: 'post',
url: '/api/elements',
data: {
name: name,
HTMLCode,
JSCode,
CSSCode,
screenshot
}
});
} catch (e) {
console.log(e);
}
}
Endpoint for POST Request
router.post("/", upload.single("screenshot"), async (req, res) => {
try {
const newElement = new Element({
name: req.body.name,
JSCode: req.body.JSCode,
HTMLCode: req.body.HTMLCode,
CSSCode: req.body.CSSCode,
screenshot: req.file.buffer,
});
await newElement.save();
res.send("Data uploaded successfully!");
} catch (e) {
console.error(e);
}
});
Server.js
const express = require("express");
const passport = require("passport");
const session = require("express-session");
const cors = require('cors');
const elementRouter = require("./routes/elementRoute");
const authRouter = require("./routes/authRoute");
const connectDB = require("./config/db");
const app = express();
const port = process.env.PORT || 5000;
connectDB();
app.use(
session({
secret: "googleOAuth",
resave: false,
saveUninitialized: true,
})
);
app.use(cors());
// Passport Config
require("./config/passport")(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use("/api/elements", elementRouter);
app.use("/api/auth", authRouter);
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
You need to install and require body-parser in your serverside code
First run npm i --save body-parser
Then require it like this
const bodyParser = require("body-parser");
Then use it after you declare your app ( after this line const app = express();)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
This makes the data of your request available in req.body

Categories