I'm trying ti deploy a NodeJS App to Azure. Everything works fine including react. but when I'm trying to hit the GraphQL server I'm getting a 404 Error
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Any Ideas?
Here is my index.js
'use strict'
require('babel-core/register')
import schema from './data/schema'
import GraphQLHTTP from 'express-graphql'
import express from 'express'
const multer = require('multer')
const insert = require('./business/insert')
const app = express()
const port = process.env.PORT || 8080
var bodyParser = require('body-parser')
app.use(bodyParser.json()) // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })) // support encoded bodies
app.use('/graphql', GraphQLHTTP({
schema,
graphiql: true
}))
app.use(express.static('public'))
app.set('view engine', 'html')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/upload/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '.xlsx')
}
})
var upload = multer({ storage: storage })
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port, () => {
console.log('Listening http://localhost:8080')
})
Judging by this document https://babeljs.io/docs/usage/require/ it appears that tooling for ES6 only happens via the next requires
All subsequent files required by node with the extensions .es6, .es, .jsx and .js will be transformed by Babel.
So you'll need something like this instead:
// app.js
'use strict'
require('babel-core/register')
require('./index')
// index.js
import schema from './data/schema'
import GraphQLHTTP from 'express-graphql'
import express from 'express'
const multer = require('multer')
const insert = require('./business/insert')
const app = express()
const port = process.env.PORT || 8080
var bodyParser = require('body-parser')
app.use(bodyParser.json()) // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })) // support encoded bodies
app.use('/graphql', GraphQLHTTP({
schema,
graphiql: true
}))
app.use(express.static('public'))
app.set('view engine', 'html')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/upload/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '.xlsx')
}
})
var upload = multer({ storage: storage })
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port, () => {
console.log('Listening http://localhost:8080')
})
Related
I am creating an app using Node, Express and ejs and multer for uploading images. Every time I submit the form, req.file is undefined. I've spent the entire day troubleshooting but can't figure out what I'm doing wrong.
HTML
<form action="/post" id="formPost" method="post" enctype="multipart/form-data">
<input class="img-file" type="file" name="image" required>
<input class="submit" type="submit" value="Post" />
</form>
app.js
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const bodyParser = require("body-parser");
const multer = require('multer');
const app = express();
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname,'resources/views'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./image");
},
filename: function (req, file, cb) {
console.log(req.file);
cb(null, Date.now() + "-" + file.fieldname + ".png");
},
});
const upload = multer({ storage: storage });
app.post("/post", upload.single("image"), (req, res) => {
console.log(req.file);
});
app.get("/post", (req, res) => {
res.render("post");
});
app.listen(, () => {
console.log(`Example app listening at http://localhost:3000/login`);
});
You have few little bugs: first you forgot to add port and instead of login it should be post then we hit the correct address immediately, avoiding error Cannot GET /login
app.listen(3000, () => {
console.log(`Example app listening at http://localhost:3000/post`);
});
Project Folder & File structure:
app.js I added simple an error handler to the:
app.post("/post", upload.single("image"), (req, res, next) => {}
const path = require("path");
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const multer = require("multer");
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "resources/views"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./image");
},
filename: function (req, file, cb) {
console.log(req.file);
cb(null, Date.now() + "-" + file.fieldname + ".png");
},
});
const upload = multer({ storage: storage });
// app.post("/post", upload.single("image"), (req, res) => {
// console.log(req.file);
// });
app.post("/post", upload.single("image"), (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error("Please upload a file");
error.httpStatusCode = 400;
return next(error);
}
res.send(file);
console.log("Success", req.file);
});
app.get("/post", (req, res) => {
res.render("post");
});
app.listen(3000, () => {
console.log(`Example app listening at http://localhost:3000/post`);
});
post.ejs
<form action="/post" id="formPost" method="post" enctype="multipart/form-data">
<input class="img-file" type="file" name="image" required />
<input class="submit" type="submit" value="Upload File" />
</form>
output:
after selecting the file and pressing upload file:
VSCode output:
Works like a charm ;-)
I've tried multer before in the past and it worked perfectly, but this time I can't get the image to load even when my path is correct and the file exists.
Here's my app.js on Node
require('dotenv').config();
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path')
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.use('/tmp/my-uploads',express.static(path.join(__dirname,'/tmp/my-uploads')))
const routes = require('./routes');
app.use(routes);
app.listen(PORT, () => {
console.log('Listening on port : ', PORT);
})
Multer Middleware
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./tmp/my-uploads");
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(
null,
file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
);
},
});
const upload = multer({ storage: storage });
module.exports = upload;
From my react front end to show the image
const image = CarsImages.filter((image) => {
if(image.primary === true){
return `http://localhost:3000/tmp/my-uploads/${image.filename}`;
}
})
Proof that the image exist, but doesnt load
screenshot
My local storage location
screenshot
Feel free to ask me further questions if you need more details
I'm trynna get the form`s data that contains a file, and I use Multer for handling that, but for some reason, my req.body is returning {}, but when I use the normal form without multipart data, it gives me all the data, so the problem is with Multer, here's my code
const express = require("express");
const app = express();
const multer = require("multer");
app.listen(8000);
let upload = multer({ dest: "uploads/" });
upload.single("logo");
app.use(express.urlencoded({ extended: true }));
app.post("/", (req, res) => {
console.log(req.file);
});
const express = require("express");
const app = express();
const multer = require("multer");
app.listen(8000);
let upload = multer({ dest: "uploads/" });
app.use(express.urlencoded({ extended: true }));
app.post("/", upload.single("logo"), (req, res) => {
console.log(req.file);
});
You need to specify upload.single as middleware.
This is working code in my project.
const path = require("path");
const multer = require('multer');
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'images');
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString()+ "-" + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) {
cb(null, true);
} else {
cb(null, false);
}
};
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(multer({ storage: fileStorage, fileFilter: fileFilter }).single('image'));
app.use(express.static(path.join(__dirname, 'public')));
app.use("/images", express.static(path.join(__dirname, 'images')));
app.post("/", (req, res) => {
console.log(req.file);
});
app.listen(5000, () => console.log("Server Started!"));
In my html I have,
<input name="password" type="password" required class="form-control" id="exampleInputPassword1">
and in my node I have,
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/login.html', (req, res) => {
res.sendFile('./login.html', {root: __dirname});
})
app.post('/login', urlencodedParser, (req,res)=>{
req.body.password
})
but, the req.body.password is undefined or empty. How do I make it actually grab what the user is inputting? It does not work for any of them but, I just used password as an example. All the packages were downloaded correctly.
Thanks.
I used the following code:
const express = require("express");
const bcrypt = require("bcrypt");
const bodyParser = require("body-parser");
const app = express();
const jsonParser = express.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
// CHANGE THIS TO DATABASE LATER OF USERS
const users = [];
//listen for requests
app.listen(3000);
app.use(express.static(__dirname + "/public"));
app.get("/index.html", (req, res) => {
res.sendFile("./index.html", { root: __dirname });
});
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", jsonParser, (req, res) => {
console.log("Hello");
console.log(req.body.password);
res.json(req.body.password);
});
app.get("/signup.html", (req, res) => {
res.sendFile("./signup.html", { root: __dirname });
});
app.post("/signup", urlencodedParser, (req, res) => {});
app.use((req, res) => {
res.sendFile("./404.html", { root: __dirname });
});
And when I send a POST request to the /login path using the following payload:
{
"password": "Check for Stack Overflow"
}
I get this on the console:
$ node app
Error: ENOENT: no such file or directory, stat '/root/404.html'
Hello
Check for Stack Overflow
I use the following end point: http://2886795314-3000-ollie08.environments.katacoda.com/
And I used POSTMan and got this right now:
Previous Answer...
You have to use res object to send something. For example, to send a JSON structure, you can do:
res.json(req.body.password)
So your code will be:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
Also I could see that you are not using a .listen or export of your modules. You may as well need to listen it to a port to run! So use:
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
At the end. So your complete file looks like:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
Also, please consider reading Express "Hello World" example. It has the best example in the easiest way possible from the original documentation.
req.body.password is kind of like a variable. It 'returns' it's value, but you're not doing anything with what it returns.
It's not clear what you mean with return. If you want to log something to a console, you can do that:
console.log(req.body.password);
I am trying to send 6 based64 images with some other data but I keep getting error entity is too large even I have added below code in my app.js file
`app.use(bodyparser.json({ limit: '50mb', extended: true }))
app.use(bodyparser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }))`
If I try with the postman then there is no error only with web application.
I am using Angular as Front-end.
I don't know why this error is occurring.
Kindly your help would be great.
Thanks in Advance.
const express = require('express');
const bodyParser = require('body-parser')
const multer = require('multer')
var fs = require('fs');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now() + '.png');
}
});
var upload = multer({ storage: storage });
const app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static('public'))
app.post('/', upload.single('file'), (req, res) => {
console.log(req.body.key1);
fs.readFile(req.file.path, function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
})
app.listen(3000);