node.js - The first argument must be of type string or an instance of Buffer with http module - ios

these day I'm new to node.js and leanrning them from Youtube vid
I had a plan to express image file to webbrowser
here is something wrong (I've already add image file in my folder)
and then I was trying to resolve this problem by searching google
but I hadn't found out.
It's first time to make a new account
it's the code
var http=require('http');
var fs = require('fs');
var server = http.createServer();
var host = '192.168.0.42';
var port = 3000;
server.listen(port,host,50000,function(){
console.log('웹서버 실행됨');
});
server.on('connection',function(socket){
var addr = socket.address();
console.log('클라이언트가 접속했습니다. : %s, %d', addr.address,addr.port);
});
server.on('request',function(req,res){
console.log('클라이언트 요청이 들어왔습니다.');
var filename = "coronavirus.png";
fs.readFile(filename, function(err,data){
res.writeHead(200, {"Content-Type":"image/png"});
res.write(data);
res.end();
});
});

your readFile needs to include an absolute or relative path.
try with a forward "/" as in /your_file_path or resolve with a cross-platform solution using __dirname + your file_path.
From the docs
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});

Related

Google Drive API - Automated Queries Message

I am using this Ghost plugin to store image data on Google Drive. Recently, images have stopped loading with this error page downloaded in place of the image:
The site is running in a containerized Ghost instance on Google Cloud Run, source here
Do I need to open a support ticket somewhere to resolve this? Site in question is here
EDIT: Here is the code used to access the saved content.
jwtClient.authorize(function(err, tokens) {
if (err) {
return next(err);
}
const drive = google.drive({
version: API_VERSION,
auth: jwtClient
});
drive.files.get(
{
fileId: id
},
function(err, response) {
if (!err) {
const file = response.data;
const newReq = https
.request(
file.downloadUrl + "&access_token=" + tokens.access_token,
function(newRes) {
// Modify google headers here to cache!
const headers = newRes.headers;
headers["content-disposition"] =
"attachment; filename=" + file.originalFilename;
headers["cache-control"] = "public, max-age=1209600";
delete headers["expires"];
res.writeHead(newRes.statusCode, headers);
// pipe the file
newRes.pipe(res);
}
)
.on("error", function(err) {
console.log(err);
res.statusCode = 500;
res.end();
});
req.pipe(newReq);
} else {
next(err);
}
}
);
});
Your problem is related to file.downloadUrl. This field is not guaranteed to work and is not supposed to be used to download files.
The correct way to do this is to use the webContentLink property instead. You can look at here for reference.

Invalid signature when trying to upload to Cloudinary

Using the Node integration provided by cloudinary_npm, I'm getting the following message back when I try to upload:
{ error: { message: 'Invalid Signature t7233823748278473838erfndsjy8234. String to sign - \'timestamp=1439054775\'.', http_code: 401 } }
I retrieve then pass my image to the backend like this:
$scope.previewFile = function() {
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
reader.onloadend = function () {
base64img = reader.result;
preview.src = base64img;
console.log(base64img);
};
};
$scope.submitPic = function() {
$http.post('http://localhost:3000/story/pic', {img: base64img})
.success(function(data){
preview.src = "";
})
.error(function(err){
console.log(err);
});
};
Then in the back, I have the following configuration and routes, both straight from the docs:
var cloudinary = require("cloudinary");
var CLOUD_API_SECRET = require("../constants.js");
cloudinary.config({
cloud_name: 'some_cloud',
api_key: '63789865675995',
api_secret: CLOUD_API_SECRET
});
router.post('/pic', function(req, res, next) {
var img = req.body.img;
cloudinary.uploader.upload(img, function(result) {
});
res.status(200).send('ok');
});
Does anyone recognize what I might be doing wrong? I've been troubleshooting this for hours. I'm at a dead end.
make sure you have placed your cloudinary secret inside a ''(quote/inverted comma).make sure the resulting statement should mean :
var CLOUD_API_SECRET ='some_cloudinary_secret_xxx';
check this value in the js file from where you are fetching this value.
From Java level I fixed this issue by changing the time zone to America/New_York time:
Long time = new Long(System.currentTimeMillis() );
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date date = new Date(sdf.format(new Date(time)));
long utcDateInMilliSeconds = date.getTime();
params.put("timestamp", new Long(utcDateInMilliSeconds/1000));
I had this very same error running similar code route on nodejs using cloudinary's sdk.
The issue turned out to be a typo within my API_SECRET.
Like Jeremy said, It's mostly typo or white space in your API secret.
Try to use your API secret directly in the configuration (not via variable)

Uploading an Image file via ajax in add-on panel

I'm trying desperately to create a Firefox add-on that posts a file with the field name "Filedata" to a particular PHP script which will only work if it sees a JPG in the $_FILE["Filedata"] variable.
I put a web form with a file browser into panel.html, then I take the image and turn it into a canvas which I turn into a blob and send to main.js. I would be happy to send the file directly from panel.js, but nothing at all happens (no error message either) when I attempt to so.
In main.js, I have this code but I get an error message that FormData doesn't exist in main.js. What to do?
function ajupload(mydata) {
var fd = new FormData();
fd.append("Filedata", mydata);
const {XMLHttpRequest} = require("sdk/net/xhr");
var myrequest = new XMLHttpRequest();
myrequest.open('POST', 'MYSITE/image.php?action=upload');myrequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
myrequest.upload.addEventListener("progress", function(e) {
var percentage = Math.round((e.loaded * 100) / e.total);
}, false);
myrequest.onreadystatechange=function()
{
if (myrequest.readyState==4 && myrequest.status==200)
{
console.log("Response" + myrequest.responseText);
}
}
myrequest.send(fd);
}

Get query string params using Restful / Resourceful / Flatiron

I have the following node app using Restful / Resourceful / Flatiron:
app.js
var flatiron = require('flatiron'),
fixtures = require('./fixtures'),
restful = require('restful'),
resourceful = require('resourceful');
var app = module.exports = flatiron.app;
app.resources = {};
app.resources.Creature = fixtures.Creature;
app.use(flatiron.plugins.http, {
headers: {
'x-powered-by': 'flatiron ' + flatiron.version
}
});
app.use(restful);
app.start(8000, function(){
console.log(app.router.routes);
console.log(' > http server started on port 8000');
console.log(' > visit: http://localhost:8000/ ');
});
Here is the fixtures module:
fixtures.js
var fixtures = exports;
var resourceful = require('resourceful');
// // Create a new Creature resource using the Resourceful library //
fixtures.Creature = resourceful.define('creature', function () {
var self = this;
this.restful = true;
this.all = function (callback) {
console.log(this);
callback(null, "ok"); };
});
How can I access the request/query string parameters? E.g. if the route is /creatures?foo=bar
I came across this issue from the Github repo, but the comments imply there may be a more long winded method of obtaining this data?
I've been looking at the source code for resourceful and I don't see a clear way. Here is the line in question:
https://github.com/flatiron/resourceful/blob/master/lib/resourceful/resource.js#L379
The default versions listed via NPM Package Manager are out of date which caused some confusion.
See the Github issue here:
https://github.com/flatiron/restful/issues/33
Using package.json in combination with NPM install works with the version combinations:
"restful": "0.4.4",
"director": "1.1.x",
"resourceful": "0.3.x",
"director-explorer": "*"
With this newer version the url format now works in the style of:
/create/find?foo=bar
The method in question is can be found here:
https://github.com/flatiron/restful/blob/master/lib/restful.js#L506
At the time of writing the method looks as follows:
router.get('/' + entity + '/find', function () {
var res = this.res,
req = this.req;
preprocessRequest(req, resource, 'find');
resource.find(req.restful.data, function(err, result){
respond(req, res, 200, entity, result);
});
});
The key component being that req.restful.data is the parsed query string data.

how to parse a request in a node.js server built on net module

We are building a server with net module, and having hard time extracting the URL (and resource path) from the request. The following code crashes, saying:
Parameter 'url' must be a string not undefined.
File netServer.js:
var net = require('net');
var url = require('url');
var server = net.createServer(function(socket) { //'connection' listener
socket.on('connect', function(request) {
});
socket.on('data', function(request) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
});
socket.on('end', function() {
});
});
server.listen(8080, function() { //'listening' listener
console.log('server bound');
});
Any suggestions?
Are you trying to build an HTTP server? net is a TCP package, so all you get is the remoteAddress and remotePort, the rest will be sent on the data handler (which is just passed a Buffer, or a string, depending on the encoding).
Use the HTTP module for this, because it does all of the parsing for you.

Resources