I'm trying to ask for a confirmation before upload the file so the server, currently I have this HTML code:
<p-fileUpload mode="basic" name="file" url="{{urlUpload}}" chooseLabel="Upload CSV (onBeforeSend)="onBeforeSend($event)">
Then, I have this TS code:
onBeforeSend (event): void {
const token = this.service.getTokenSession();
event.xhr.setRequestHeader('Authorization', 'Bearer ' + token);
this.confirmationService.confirm({
message: 'Are you sure to continue?',
header : 'Confirmation',
accept : () => {
this.service.showLoader();
this.onUpload(event);
},
reject: () => {}
});
}
onUpload(event): void {
this.msgsPage = [];
try {
const response = JSON.parse(event.xhr.response);
console.log(response)
if (!response.ok) {
this.errorModalService.show('There was an error');
this.flagResultLoadErrors = true;
let c = 0;
for (let msg of response.map.errors) {
c++;
this.msgsPage.push({
detail : msg,
severity: 'error',
summary : 'Error ' + c,
});
}
}
} catch (e) {
this.errorModalService.show('Unknown error');
console.log(e)
} finally {
this.service.hideLoader();
}
}
With this, I tried to block the request, but it didn't happen, what I got is that the file is sent to the server before the confirmation dialog.
Also, I'm getting this error when I tried to get the response:
SyntaxError: Unexpected end of JSON input
Hope you can help me.
You can't block from that event. It is just an event emitted from the component.
https://github.com/primefaces/primeng/blob/master/src/app/components/fileupload/fileupload.ts#L367
You will need to use the custom uploadHandler.
<p-fileUpload name="myfile[]" customUpload="true" (uploadHandler)="myUploader($event)"></p-fileUpload>
myUploader(event) {
//event.files == files to upload
}
SyntaxError: Unexpected end of JSON input
This one means the response you are getting from the xhr response is not JSON, but you are trying to parse it. Check network tab to see what the response from the server is.
Related
i am currently building an frontend app to display a generated qr code from an api. I started to implement the code but got a problem with the parsing of the response
here is the frontend code with the call
<template>
<div>
<p>test</p>
</div>
</template>
<script>
// Configuration
let myConfiguration = {
"Account" : "CH4431999123000889012",
"CreditorName" : "Muster AG",
"CreditorAddress1" : "Hauptstrasse 1",
"CreditorAddress2" : "8000 Zürich",
"CreditorCountryCode" : "CH",
"DebtorName" : "LivingTech GmbH",
"DebtorAddress1" : "Dörflistrasse 10",
"DebtorAddress2" : "8057 Zürich",
"DebtorCountryCode" : "CH",
"Amount" : "1.50",
"ReferenceNr" : "21000000000313947143000901",
"UnstructuredMessage" : "Mitteilung zur Rechnung",
"Currency" : "CHF",
"QrOnly" : "false",
"Format" : "PDF",
"Language" : "DE"
}
// Call function to create invoice
let myFile = generateQrInvoice(myConfiguration);
// Work with binary data
if(myFile != null) {
// ...
}
function generateQrInvoice(myRequestConfiguration) {
// Main configuration
let myEndpointUrl = "http://qrbillservice.livingtech.ch";
let myEndpointPath = "/api/qrinvoice/create/";
let myApiKey = "(falseApiKey)";
// GET parameters
let myGetParams = new URLSearchParams(myRequestConfiguration);
// Perform request
fetch(myEndpointUrl + myEndpointPath + "?" + myGetParams, {
method: "GET",
mode: "cors",
cache: "no-cache",
headers: {
"APIKEY": myApiKey,
"Accept": "application/json"
}
}).then(function (myResponse) {
try {
// Check status
if(myResponse.status == 200) {
// Read and parse JSON
let myJsonObject = JSON.parse(myResponse);
// Check if error
if(myJsonObject["isSuccessed"] == "true") {
if("base64Content" in myJsonObject && myJsonObject["base64Content"].trim() != "") {
// E.g. send file to client
let myBlob = new Blob(atob(myJsonObject["base64Content"]), {type: "application/pdf"});
let myBlobUrl = URL.createObjectURL(myBlob);
window.open(myBlobUrl);
// Return data
return atob(myJsonObject["base64Content"]);
} else {
throw "no data provided";
}
} else {
throw myJsonObject["message"];
}
} else {
throw "status code " . myResponse.status;
}
}
catch(e) {
// Handle exception
console.warn("Error: " + e.message, e);
return null;
}
}).catch(function (err) {
// Handle exception
console.warn("Error: " + err.message, err);
return null;
});
}
</script>
and here is the response i get when i inspect on the browser :
Error: Unexpected token 'o', "[object Response]" is not valid JSON SyntaxError: Unexpected token 'o', "[object Response]" is not valid JSON
at JSON.parse (<anonymous>)
at app.vue:61:42
I didn't write the apikey here but it is written on my code.
As it has been a long time since i didn't code like this, i don't really see yet how to tackle the problem. I tried to test with postman but it appears my request is not good yet.
If someone has an idea, i would be very happy to learn.
Thank you very much in advance,
Eugene
So i test myResponse and it is a JSON.
However the problem remains : i saw in the console that the api answers successfully api response
So i figured that i could just replace
let myJsonObject = JSON.parse(myResponse)
by
let myJsonObject = myResponse
and try to see what goes.
Now it goes directly in the catch(e) and send me an error response.
It looks like in my code, i don't go in the right direction to use the information i got from the api.
Here is partially the information i got : {"isSuccessed":true,"statusCode":200,"mimeType":"application/pdf","message":"QrBill is successfully generated","isQrOnly":false,"errors":"null","base64Content":(here is the content, i didn't added because it is quite long)}
my question therefore is how could recover the pdf and show it to the end user?
As the title states, I have a variable which is a javascript object, i'm comparing it with another js object by stringifying them. The problem is that the variable is completely accessible without calling the keys, so these
if(JSON.stringify(response) == JSON.stringify(lastcmd))
if(JSON.stringify(response.id) == JSON.stringify(lastcmd))
work perfectly fine, but accessing lastcmd's id key will cause it to throw undefined.
if(JSON.stringify(response) == JSON.stringify(lastcmd.id))
full code link here
Edit: Here's the JSON
{ "id" : "001", "app": "msgbox", "contents": { "title": "Newpaste", "message": "I'm a edited paste!" } }
Edit2: Here's the code on the post
const { BrowserWindow, app, dialog, ClientRequest } = require("electron");
const axios = require("axios");
const url = require("url");
let win = null;
let lastcmd;
function grabCurrentInstructions(fetchurl) {
return axios
.get(fetchurl)
.then(response => {
// handle success
//console.log(response.data);
return response.data;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
function boot() {
//console.log(process.type);
win = new BrowserWindow({
resizable: true,
show: false,
frame: false
});
win.loadURL(`file://${__dirname}/index.html`);
//Loop everything in here every 10 seconds
var requestLoop = setInterval(getLoop, 4000);
function getLoop() {
grabCurrentInstructions("https://pastebin.com/raw/i9cYsAt1").then(
response => {
//console.log(typeof lastcmd);
//console.log(typeof response);
if (JSON.stringify(response.app) == JSON.stringify(lastcmd.app)) {
console.log(lastcmd.app);
clearInterval(requestLoop);
requestLoop = setInterval(getLoop, 4000);
} else {
lastcmd = response;
switch (response.app) {
case "msgbox":
dialog.showMessageBox(response.contents);
//console.log(lastcmd);
clearInterval(requestLoop);
requestLoop = setInterval(getLoop, 1000);
}
}
}
);
}
}
app.on("ready", boot);
And here's the error:
(node:7036) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at grabCurrentInstructions.then.response (C:\Users\The Meme Machine\Desktop\nodejsprojects\electronrat\index.js:42:64)
at process._tickCallback (internal/process/next_tick.js:68:7)
Thanks to user str I saw that my lastcmd was undefined when I ran the comparison the first time, this would break it and thereby loop the same error over and over, by addding
grabCurrentInstructions("https://pastebin.com/raw/i9cYsAt1").then(
response => {
lastcmd = response;
}
);
below this line
win.loadURL(`file://${__dirname}/index.html`);
I made sure that the last command sent while the app was offline wouldn't be executed on launch and fixing my problem at the same time!
I'm trying to get a json from "nightmare" in Node.js and then use JSON.parse(), but I'm getting the following error:
(node:9748) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected token ☻ in JSON at position 18509
My code:
var nightmare = Nightmare()
.goto('URL')
.wait(10000) // Need wait some time
.evaluate(() => {
return document.body.innerText;
})
.end()
.then((body) => {
var data;
try {
data = JSON.parse(body);
} catch(e) {
console.log(e);
}
callback(null, data);
});
You can check if the JSON is valid or not simply using the JSON.parse function as you are using.
function validJSON(str) {
try {
// try to parse the JSON
JSON.parse(str);
} catch (e) {
// if not a json
return false;
}
// if it's valid json
return true;
}
It'll check if the string is valid json or not. Now, you can use it with your nightmareJS.
const nightmare = Nightmare()
.goto("URL")
.wait(10000) // Need wait some time
.evaluate(() => {
return document.body.innerText;
})
.end()
.then(body => {
// if it's a valid json, send it,
// otherwise send it as a body object
const data = validJSON(body) ? body : { body };
callback(null, data);
});
Now, the error is showing because you said to catch(e) and console.log(e) the error. Thus it's simply obeying your command.
Since the emoji itself is not a valid json, you have to either make a json from it, or parse it if it was a json string.
A valid json object might look like this,
{emoji: "☻"}
You see how it's all quoted?
I would like to return the result of an HTTP request in my AWS Lambda function:
var http = require('http');
exports.someFunction = function(event, context) {
var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
http.get(url, function(res) {
context.succeed(res);
}).on('error', function(e) {
context.fail("Got error: " + e.message);
});
}
It should return exactly what I get when I open the url directly in my browser (try it to see the expected json).
AWS Lambda return the following error message when I call context.succeed(res):
{
"errorMessage": "Unable to stringify body as json: Converting circular structure to JSON",
"errorType": "TypeError"
}
I assume that I need to use some property of res instead of res itself, but I couldn't figure out which one contains the actual data I want.
If you are using the raw http module you need to listen for data and end events.
exports.someFunction = function(event, context) {
var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
http.get(url, function(res) {
// Continuously update stream with data
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(body);
});
res.on('error', function(e) {
context.fail("Got error: " + e.message);
});
});
}
Using another module such as request https://www.npmjs.com/package/request would make it so you don't have to manage those events and your code could go back to almost what you had before.
Here's a Node.js function. It works, in the sense that bad JSON data is kicked out, but it also flashes the message that it failed. Why?
// Create document
app.post('/documents.:format?', loadUser, function(req, res) {
/////////////////////////added by adam
//tests to see if the inputed text is valid JSON data
data = req.body.d.data;
console.log("///////////" + data);
try {
type = JSON.parse(data);
console.log(type);
} catch (ex) {
console.log("bad json: "+data);
req.flash('Nope', 'Invalid JSON');
res.redirect('/documents');
return;
}
var d = new Document(req.body.d);
d.user_id = req.currentUser.id;
d.save(function() {
switch (req.params.format) {
case 'json':
res.send(d.toObject());
break;
default:
req.flash('info', 'Document created');
res.redirect('/documents');
}
});
The catch block contains both the error message and the 'bad JSON' logger, so they will always occur at the same time, due to the block scope.