Loading image server node.js - image

im trying to load image and when I check on the browser if works, it say not found, any ideas of how to fixed.
Thank you
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': body.length
});
res.end(img, 'binary');
};
exports.init = function(cb) {
require('fs').readFile('./image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}

Related

`next.js` api is resolved before promise fullfill?

I want to achieve something like this:
call my website url https://mywebsite/api/something
then my next.js website api will call external api
get external api data
update external api data to mongodb database one by one
then return respose it's status.
Below code is working correctly correctly. data is updating on mongodb but when I request to my api url it respond me very quickly then it updates data in database.
But I want to first update data in database and then respond me
No matter how much time its take.
Below is my code
export default async function handler(req, res) {
async function updateServer(){
return new Promise(async function(resolve, reject){
const statusArray = [];
const apiUrl = `https://example.com/api`;
const response = await fetch(apiUrl, {headers: { "Content-Type": "application/json" }});
const newsResults = await response.json();
const articles = await newsResults["articles"];
for (let i = 0; i < articles.length; i++) {
const article = articles[i];
try {
insertionData["title"] = article["title"];
insertionData["description"] = article["description"];
MongoClient.connect(mongoUri, async function (error, db) {
if (error) throw error;
const articlesCollection = db.db("database").collection("collectionname");
const customQuery = { url: article["url"] };
const customUpdate = { $set: insertionData };
const customOptions = { upsert: true };
const status = await articlesCollection.updateOne(customQuery,customUpdate,customOptions);
statusArray.push(status);
db.close();
});
} catch (error) {console.log(error);}
}
if(statusArray){
console.log("success", statusArray.length);
resolve(statusArray);
} else {
console.log("error");
reject("reject because no statusArray");
}
});
}
updateServer().then(
function(statusArray){
return res.status(200).json({ "response": "success","statusArray":statusArray }).end();
}
).catch(
function(error){
return res.status(500).json({ "response": "error", }).end();
}
);
}
How to achieve that?
Any suggestions are always welcome!

Getting 429 (Too Many Request) in vue.js laravel

I'm using vue.js and laravel when i open edit page i get this error in my console but Update function is called on button click and bill url is also called multiple times without parameter on mounted function
app.js:1088 GET http://localhost:8000/api/userbackend/bill/undefined 404 (Not Found)
POST http://localhost:8000/api/userbackend/Update 429 (Too Many Requests)
Code Snippet:
async mounted(){
this.roleid = this.userData.role_id;
const header = {
'Authorization': 'Bearer ' + this.LoginUserData,
};
this.editId = this.$route.params.id;
if(this.$route.params.id !== undefined) {
try{
let response = await axios.get(`/api/userbackend/bill/${this.editId}` ,{headers: header});
this.form = response.data;
}
saveRecord(){
let loader = this.$loading.show();
let formData = new FormData();
formData.append('id', this.editId);
....
const header = {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + this.LoginUserData,
};
axios.post('/api/userbackend/Update', formData ,{headers: header}).then((response) =>{
loader.hide();
if(response.data.status == true){
.....
}
})
.catch((response) => {
loader.hide();
this.showErrorMsg();
});
},
validateBeforeSubmit(e) {
e.preventDefault();
let app = this;
this.$validator.validateAll().then((result) => {
if (result) {
app.saveRecord();
return;
}
this.showWarningMsg();
});
}
Any suggestion is highly appreciated

Network Request failed while sending image to server with react native

i want to send image to a server and getting the result with a json format but the application returns a Network Request failed error
react native 0.6 using genymotion as emulator
i tried RNFetchblob but the result take a long time to get response (5 min )
also i tried axios but it response with empty data with 200 ok
this is the function that import the image
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
and this method that sends the image
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.avatarSource , name:'file.jpeg'});
fetch(url, {
method: 'POST',
body:UplodedFile
})
.then(response => response.json())
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
i expect json format
ScreenShot here
can you change your code like this?
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
pickerResponse: response,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.pickerResponse.path , name:'file.jpeg'});
axios({
method: "post",
url: url,
data: UplodedFile
})
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});

Socket.io, saved image on server isn't opened

I'm trying to save image from canvas on server, but image isn't opened (isn't supported format).
Client:
const canvas = document.getElementById('canvas');
var sendData = () => {
const dataURL = canvas.toDataURL();
socket.emit('sendImage', dataURL.toString('base64'));
};
Server:
io.on('connection', function(socket) {
socket.on('sendImage', (imageData) => {
fs.writeFile(__dirname + '/image.png', imageData, function (err)
{
if (err) throw err;
console.log('It\'s saved!');
});
});
});
I found solution.
Client:
dataURL.toString('base64') has base64 encoded data in the format of
data:image/png;base64,/9j/4AAQSkZJRgABA…
So we need to get rid of the mime type and encoding information at the front.
var sendData = () => {
const dataURL = canvas.toDataURL().toString('base64');
const toSend = dataURL.split(',')[1];
socket.emit('sendImage', toSend);
};
Server:
Now we need to convert its buffer.
fs.writeFile(__dirname + '/image.png', Buffer.from(imageData, 'base64'), function
(err) {
if (err) throw err;
console.log('It\'s saved!');
});

Cannot POST ajax request

can anyone explain to me why i cannot post the ajax request. When i run this code the console appear POST http://localhost:8080/api/users 404 (Not Found), and in the networth part the preview is 404 not found
In the index.js file
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev.js');
var app = express();
var compiler = webpack(config);
var bodyParser = require('body-parser');
var users = require('./server/routes/users');
app.use(bodyParser.json());
app.use('/api/users', users);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(8080, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:8080');
});
and the users file
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
function validateInput(data) {
let errors = {};
if (Validator.isNull(data.username)){
errors.username = "This field is required";
}
if (Validator.isEmail(data.email)) {
errors.email = "Email is invalid";
}
if (Validator.isNull(data.password)){
errors.password = 'This field is required';
}
if (Validator.isNull(data.passwordConfirmation)){
errors.passwordConfirmation = 'This field is required';
}
if (Validator.equals(data.password, data.passwordConfirmation)){
errors.passwordConfirmation = 'Password must match';
}
return {
errors,
isValid: isEmpty(errors)
}
}
router.post('/api/users', (req, res) => {
console.log('runiing the router/post');
console.log(req.body);
const {errors, isValid} = validateInput(req.body);
if (!isValid) {
res.status(400).json(errors);
}
});
module.exports = router
in users.js file the function should be
router.post('/', (req, res) => {
console.log('runiing the router/post');
console.log(req.body);
const {errors, isValid} = validateInput(req.body);
if (!isValid) {
res.status(400).json(errors);
}
});
Because index.js have already resolved /api/users part in the request url http://localhost:8080/api/users at this point. So you only have to map after the /api/users in your users js file.
For example, if you have following function in users.js file
router.post('/:id', (req, res) => {
...
}
It will resole to the path http://localhost:8080/api/users/1
Edit
In your existing version,
router.post('/api/users', (req, res) => {
...
}
will resolve as http://localhost:8080/api/users/api/users

Resources