Home>
Send the Base64 encoded image from the client in JSON,
I want to receive it at the server.
To check if JSON is properly received on the server side, useconsole.log (req.body)
When trying to display on the console
{}
It was only displayed and seemed not to be able to receive JSON.
-When I confirmed that the client side developer tool was able to encode it properly, there seemed to be no problem.
I tried・console.log (req.body)
withconsole.log (req.body.data)
, butundefind
.
・body-parser
, but it was not.
var createError = require ('http-errors');
var express = require ('express');
var path = require ('path');
var cookieParser = require ('cookie-parser');
var logger = require ('morgan');
var indexRouter = require ('./ routes/index');
var usersRouter = require ('./ routes/users');
var app = express ();
// view engine setup
app.set ('views', path.join (__ dirname, 'views'));
app.set ('view engine', 'jade');
app.use (logger ('dev'));
app.use (express.json ());
app.use (express.urlencoded ({extended: false}));
app.use (cookieParser ());
app.use (express.static (path.join (__ dirname, 'public')));
app.use ('/', indexRouter);
app.use ('/ users', usersRouter);
// catch 404 and forward to error handler
app.use (function (req, res, next) {
next (createError (404));
});
// error handler
app.use (function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get ('env') === 'development'? err: {};
// render the error page
res.status (err.status || 500);
res.render ('error');
});
app.listen (8080);
module.exports = app;
// const model = await cocoSsd.load ();
var express = require ('express');
var router = express.Router ();
router.use (express.json ());
router.use (express.urlencoded ({extended: true}));
// Transit to the image upload screen
router.get ('/', function (req, res, next) {res.sendfile ("./ public/index.html");
});
// Where JSON is sent from the client
router.post ("/ upload", function (req, res, next) {
console.log (req.body);
// Hereafter omitted
});
module.exports = router;
Client side
<! DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<script
src = "https://code.jquery.com/jquery-3.4.1.min.js"
integrity = "sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo ="
crossorigin = "anonymous">
</script>
<title>Upload image</title>
</head>
<body>
Upload image
<!-File selection button->
<form enctype = "multipart/form-data" method = "post">
<input type = "file" name = "userfile" accept = "image/*">
</form>
<!-Thumbnail display area->
<canvas width = "0" height = "0"></canvas>
<!-Upload start button->
<button>Post</button>
<!-Below, javascript->
<script type = "text/javascript">
$(function () {
var file = null;// selected file
const THUMBNAIL_WIDTH = 640;// Horizontal length after image resizing
const THUMBNAIL_HEIGHT = 480;// Vertical length after image resizing
var base64;// Substitute this variable when Base64 encoded
// Once the file is selected
$('input [type = file]'). change (function () {
// get the file
file = $(this) .prop ('files') [0];
// Determine if the selected file is an image
if (file.type! = 'image/jpeg'&&file.type! = 'image/png') {
// end if not an image
file = null;
blob = null;
return;
}
// resize the image
var image = new Image ();
var reader = new FileReader ();
reader.onload = function (e) {image.onload = function () {
var width, height;
width = THUMBNAIL_WIDTH;
height = THUMBNAIL_HEIGHT;
// Change the size of the canvas for thumbnail drawing to the value declared as a constant
var canvas = $('# canvas')
.attr ('width', THUMBNAIL_WIDTH)
.attr ('height', THUMBNAIL_HEIGHT);
var ctx = canvas [0] .getContext ('2d');
// clear image already drawn on canvas
ctx.clearRect (0,0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
// draw thumbnails on canvas
ctx.drawImage (image, 0,0, image.THUMBNAIL_WIDTH, image.THUMBNAIL_HEIGHT, 0,0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
// Get base64 image data from canvas
base64 = canvas.get (0) .toDataURL ('image/jpeg');
console.log (base64);// For testing
}
image.src = e.target.result;
}
reader.readAsDataURL (file);
});
// When the upload start button is clicked
$('# upload'). click (function () {
$.ajax ({
url: "http: // localhost: 8080/upload", // destination
type: 'POST',
dataType: 'json',
data: {
"src": base64,
},
processData: false,
contentType: false
})
.done (function (data, textStatus, jqXHR) {
// successful transmission
})
.fail (function (jqXHR, textStatus, errorThrown) {
// Transmission failure
});
});
});
</script>
</body>
</html>
How can I receive JSON?
Thank you.
Node.js v12.13.0
npm v6.12.0
Express v4.16.1
Browser used: Google Chrome
-
Answer # 1
Related articles
- nodejs express cannot receive jqueryajax post
- nodejs - cannot do vue create
- json - [typescript] tsc --init cannot be executed error ts5023: unknown compiler option 'init'
- javascript - cannot copy files using fs with nodejs
- javascript - identifying buttons with nodejs + express
- nginx settings when deploying nodejs (express)
- how to not send nodejs express error to browser side
- javascript - i want to list in db connection of nodejs + express + sql server
- json - about the "cannot write to user settings" error in ms vs code that i asked before
- nodejs cannot be confirmed with terminal
- nodejs - cannot mount host os folder and container directory with docker
- nodejs - cannot access nas node from outside
- nodejs - package installed with yarn cannot be imported from within js
- nodejs - cannot run npm run dev (cannot find module 'babel-plugin-transform-vue-jsx')
- link between nodejs and json file does not work
- api - in express, when resjson (), header cannot be set
- nodejs - electron cannot be installed
- processing when starting and ending the express server of nodejs
- javascript - about nodejs express appuse
- i want to make columns variable with express + mysql of nodejs
Related questions
- json - i want to solve the warn that appears when installing express
- javascript : .Json file is not output to the console
- javascript - i want to do server side, but i'm at a loss with firebase and express
- i want to daemonize what was developed with nodejs + webpack in production
- api - json-server requires at least version 10 of node, please upgrade
- javascript - an error occurs when displaying the parsed json data in the log
- javascript - event-driven communication with mysql with angular + express
- json - gulp-stylelint does not respond stylelint: undefined rule unicode-bom
- postgresql - [nodejs] i want to perform like search for date type with sequelize
- postgresql - i got a command error when trying to connect to db with nodejs (express)
Since the JSON that should have been sent has not been sent, the cause is thought to be on the client side, and when the client side was investigated, the cause was found.
Cause Code before modificationExcerpts
$. ajax ()
options setprocessDataand
contentType
tofalse
Seems to have been bad.About
processData
Source
I want to send something other than JSON! It seems to be good to set it to
false
at that time.About
content-type
Source
Modified source codeSend with this kind! I'm not sure ... If you want to send JSON, it seems to be good to set the initial value.
Excerpts
Neat code ^^
You can't copy and paste code. I have to understand it properly.Thank you for the answer!