create-react-app: "The development server has disconnected. " - javascript

There are several questions about this error, but none of them fit exactly my circunstances. Let me explain: I'm writing some code using create-react-app that makes an AJAX call to an external server:
async ajaxCall(url) {
var objetorespuesta = null;
try {
let respuesta = await fetch(url);
if (respuesta.ok) {
objetorespuesta = {
"status": { status: "ok" },
"datos": await respuesta.json()
};
}
else {
objetorespuesta = {
"status": {
status: "error",
errorcode: respuesta.status,
errortext: respuesta.statusText
}
};
}
}
catch (e) {
console.log("Call failed!!");
objetorespuesta = {
"status": {
status: "error",
errorcode: "Error de red",
errortext: e
}
};
}
return objetorespuesta;
}
let url = "https://blablabla" //My URL here; edited out;
const objetorespuesta = this.ajaxCall(url);
for (let key in objetorespuesta) {
console.log("Mooooo: " + key + ": " + objetorespuesta[key]);
}
Now, before I added the "try/catch" block, I got in the console an:
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
The development server has disconnected. Refresh the page if necessary
Which I believe it's because of CORS, since I'm not calling localhost but an external URL. I'll deal with that later, but for the moment I decided to add the "try/catch" so that the code catches that error and can keep executing...
...except that it doesn't do that. When the error happens, nothing gets executed anymore. What I mean is that if the code worked, the network call would fail, but I'd get several "Mooooo" messages in the console with the variables of the returned object. Instead, what I get is:
Call failed!!
The development server has disconnected. Refresh the page if necessary.
It seems that the development server get disconnected right after the network call fails.
What's going on? The development server fails, but the JS code is being executed in my browser, so it should have no influence, right? Or is there some other error in my code that I'm missing?

Related

nodejs app crash on openai dall-e 2 api rejected request

I'm surely dumb, but I'm not able to figure out how to handle openai api rejected requests
( for the context, dall-e 2 is an image generator )
when user tries to generate forbidden images, my nodejs app just exits
async function start(arg) {
try{
// generate image
const response = openai.createImage({
prompt: arg,
n: 1,
size: "1024x1024",
});
// on success response
response.then(res =>{
console.log("ok");
})
response.catch(err =>{
console.log(err);
});
} catch(e){
console.log(e);
}
}
it gives me something like that on the exit :
data: {
error: {
code: null,
message: 'Your request was rejected as a result of our safety system. Your prompt may contain text that is not allowed by our safety system.',
param: null,
type: 'invalid_request_error'
}
}
tried using response.catch and try catch without success, the app just exits everytime
I at least want to ignore this error in the first place
in a second hand, I would like to console.log the given message (data.error.message)
I don't know what to do to by honest, don't even understand why try catch isn't working
With the details given, my guess would be that the Promise returned by getImages is being rejected. You could debug this a bit by adding some additional logs into your .catch callback and catch statement.
How to do this really depends on what you're trying to do with this api, the code as it's currently written would log something and exit no matter what happens.
There's a couple ways to handle this
Use your .catch to handle the error. Utilizing promise chainability you can get something like this
openai.createImage({
prompt: arg,
n: 1,
size: "1024x1024",
user: msg.author.id,
})
.catch((e) => {
if (e.data.error.message.includes('safety system')) {
return 'something'
}
console.error(e)
})
If you need the response object, the asnwer might be different. Looks like the openai package is built on axios and you can pass axios options into it. See https://axios-http.com/docs/handling_errors and the Request Options section of https://npmjs.com/package/openai
EDIT
I found my solution thanks to #JacksonChristoffersen
Basically I was getting http status 400
I just added request options from axios to validate http status smaller than 500
Here's the solution:
async function start(arg) {
try{
// generate image
const response = openai.createImage({
prompt: arg,
n: 1,
size: "1024x1024",
},{
validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500
}
});
// on success response
response.then(res =>{
console.log("ok");
})
response.catch(err =>{
console.log(err);
});
} catch(e){
console.log(e);
}
}

Axios does not send appropriate error response [React]

I'm trying to handle the error responses from Axios with React, but when i try to console log it the error is Network error and the error.response is undefined.
The request is a simple POST with the Authorization header correctly setted, when I try to do the same request on Postman it works correctly and I'am able to see the error response.
The request is made after the user fills a form and click on a button.
async function create() {
const response = await Axios.post(
"/api/disposal-requests/", // the base url is setted when the application mounts `Axios.defaults.baseURL = process.env.REACT_APP_API_URL`
{
description: "Description",
url: "Url",
key: "Key",
location_geoname_id: "City",
}
);
return response.data;
}
When a user clicks on a button there is another function that calls the create.
async function onClick() {
try {
await create();
// Everything works fine when there are no errors
} catch(error) {
// Here error.response is undefined
}
}
This is what i receive in the console.log, in the Network tab I can see the error status is 400 but even there there is no error response, I'am able to see the error response only on Postman.
Does anyone know what's wrong here ?
Please write await before creat(). so that if any any error occurs, catch with get that
async function onClick() {
try {
await create();
// Everything works fine when there are no errors
} catch (error) {
// Here the error response is undefined
}
}

ZeroMQ.js: With zmq.Pair, if socket.send() is called outside of an async loop, then the messages will not not received by the receiver

My setup
macOS 10.15.7
zeromq.js: v6.0.0-beta.6
node.js: v14.4.0
I'm using ZeroMQ.js to communicate between my app's frontend and backend.
The pattern in use is zmq.Pair. And the client, a.k.a. the frontend, can receive messages from the server, a.k.a. the backend, just fine.
Code
class UiBridge {
constructor(address="tcp://127.0.0.1:25555") {
this.address = address;
this.socket = new zmq.Pair();
}
async Start() {
await this.socket.connect(this.address);
console.log("frontend: Connected to backend.");
const listen = async () => {
for await (const [backendRequest] of this.socket) {
switch (backendRequest.toString()) {
case 'msg1':
onMsg1();
// THIS Send works!
// the receiver gets the reply.
this.Send("reply");
break;
case 'term':
this.Stop();
break;
default:
console.error(`undefined message from backend: ${backendRequest}`);
}
}
}
listen();
}
async Stop() {
if (!this.socket.closed) {
this.socket.close()
}
}
async Send(cmd) {
try {
await this.socket.send(cmd);
alert(`sent msg: ${msg}`);
} catch (err) {
alert(`send failed due to : ${err}`);
}
}
}
Note that if I send message inside the listening loop on receiving any message from the other side, then the send works.
Problem
But if I send messages outside of this listening loop anywhere else in the frontend code, then the other end never receives the sent message, and no exceptions are caught. Like in a button callback
function onToggleButton() {
// This is never received!
gUiBridge.Send("from frontend");
}
The button callback is triggered and I see the alert coming up. I've made sure that I can already receive messages from the server before clicking on buttons.
Workaround
I had to create another pair of PUSH/PULL to send messages from anywhere of my frontend to backend, so that I'm not blocked by this issue. But this is suboptimal.
Question
Is this by design or am I doing anything wrong?

Dialogflow api call works, but chatbot shuts off

In Dialogflow, i use the free edition (V2) with the blaze plan from Firebase.
I have an Intent that works on the word "test". When i enter "test" in the simulator, the chatbot gives an non response and leaves the chat. It is suppose to make an call to my API and retrieves information.
The weird part is, there is a console.log that prints out the body and that returns the JSON from the API. So that means the API call works fine, but there is still an error somewhere within the bot.
I found this question: Dialogflow v2 error “MalformedResponse 'final_response' must be set”
It looks alot like my problem, yet i cant seem to figure out what i should change to make mine work.
Thanks in advance for your time.
The Fulfullment:
function testcommand(agent) {
callNPApi().then((output) => {
agent.add(output);
}).catch(() => {
agent.add("That went wrong!");
});
}
function callNPApi() {
return new Promise((resolve, reject) => {
request2(url, function (error, response2, body){
//The substring is too ensure it doesnt crash for the character limit yet
body = body.substring(1,10);
console.log('Api errors: ' + JSON.stringify(error));
console.log('Api body: ' + JSON.stringify(body));
if (error) {
reject();
}
resolve('api call returned: ');
});
});
}
The Response in the console:
{
"responseMetadata": {
"status": {
"code": 10,
"message": "Failed to parse Dialogflow response into AppResponse because of empty speech response",
"details": [
{
"#type": "type.googleapis.com/google.protobuf.Value",
"value": "{\"id\":\"bca7bd81-58f1-40e7-a5d5-e36b60986b66\",\"timestamp\":\"2018-09-06T12:45:26.718Z\",\"lang\":\"nl\",\"result\":{},\"alternateResult\":{},\"status\":{\"code\":200,\"errorType\":\"success\"},\"sessionId\":\"ABwppHFav_2zx7FWHNQn7d0uw8B_I06cY91SKfn1eJnVNFa3q_Y6CrE_OAJPV-ajaZXl7o2ZHfdlVAZwXw\"}"
}
]
}
}
}
The Error in the console:
MalformedResponse
'final_response' must be set.
Yup, this is the same problem.
The issue is that you're returning a Promise from callNPApi(), but your event handler (which I assume is testcommand()) isn't also returning a Promise. If you are doing async calls anywhere in your handler, you must use a Promise, and if you are using a Promise you must also return that Promise from the handler.
In your case, this should be a simple change. Simply add "return" to your handler. So it might look something like this
function testcommand(agent) {
return callNPApi().then((output) => {
agent.add(output);
}).catch(() => {
agent.add("That went wrong!");
});
}

`EPIPE` error while testing POST request using Jest

I have a simple server which accepts POST requests and responds with the 413 Request entity too large error if the request body exceeds allowed size. When I'm testing it using Jest the request sometimes returns correct error, but more often it returns { code: EPIPE, syscall: write } error.
I tested server using cURL and from node javascript file and the server worked as expected, but Jest testing still gives me that error. I also tried another request libraries, they gave the same error.
beforeAll(() => {
server.listen(testingPort);
});
afterAll(() => {
server.close();
});
describe("POST request", () => {
test("should return error 413 in respense to exceeded file size", async () => {
const fileContent = new Array(1024 * 1024 + 10).join("*");
const fileName = "post-test-file.txt";
const urlObj = new URL(fileName, host);
try {
await axios.post(urlObj.href, fileContent);
} catch (e) {
console.log(e.code, e.errno, e.syscall); // EPIPE EPIPE write
// expect(e.response.status).toBe(413);
}
});
Maybe you have any thoughts about this?
It seems that the issue is very old and not quite resolved:
https://github.com/nodejs/node/issues/947
For me the workaround is using a stream.

Categories

Resources