I need to send data to backend, but I am having this error:
Uncaught (in promise) Error: Request failed with status code 404
How can I solve this??
Image below:
Code javascript below:
handleClick(_success, _error) {
const usuarioLogin = this.props.cliente;
const usuarioCliente = parseInt(this.state.usuario);
const ObjetoChamado = {
titulo: this.state.titulo,
descricao: this.state.descricao,
area: parseInt(this.state.area),
categoria: parseInt(this.state.categoria),
servico: parseInt(this.state.servico),
usuario: usuarioLogin,
cliente: usuarioCliente,
};
this.props.abrirChamado(
ObjetoChamado,
(response) => {
this.props.getChamados(usuarioLogin, null, (chamados) => {
// Chamado aberto, atualizar lista e fechar o popup de abertura
this.props.setClientData(usuarioLogin, null, chamados.data.objeto);
this.props.visible(false);
});
},
(error) => {
alert(!!error ? error : 'Não foi possível abrir o chamado.');
}
);
axios.post(ObjetoChamado).then((response) => {
const data = response.data;
// if (Object.keys(data).length > 0) {
// if (typeof _success === 'function') _success(data);
// } else {
// if (typeof _error === 'function') {
// _error({
// code: 404,
// message: 'Não há nenhum registro para este cliente.',
// });
// }
// }
console.log('DATA:', data);
});
};
status code 404 means that the API path that you have provided in the axios is not valid. So you need to check the API path.
axios.post(ObjetoChamado) - this is wrong.
You need to pass two arguments to axios.post, first one would the API path at which you want to send the data and second argument would be the data object.
SO your code would look something like this -
axios.post('/your-api-path', objectoChamado).then(response => {
});
Related
I ask the user to give the message id to react and my bot crash even in a try catch if the message id is wrong. I'd like to return 'This message doesn't exist'.
Here the part of code
const filter = m => m.author.id === message.author.id;
message.reply("veuillez indiquer l'id du message");
message.channel.awaitMessages(filter, {
max: 1,
time: 600000,
errors: ['time']
}).then(async(collected) => {
msgid = collected.first().content;
try{
channelid.messages.fetch(msgid);
isMsg = true;
}catch{
message.reply("Ce message n'existe pas");
}
}).catch(() => {
message.reply("Vous avez mis trop de temps a répondre");
})
And I get this error
D:\Storage\Bureau\Projets\Dev\Bots\Discord\Bot\node_modules\discord.js\src\rest\RequestHandler.js:154
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Unknown Message
at RequestHandler.execute (D:\Storage\Bureau\Projets\Dev\Bots\Discord\Bot\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async RequestHandler.push (D:\Storage\Bureau\Projets\Dev\Bots\Discord\Bot\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async MessageManager._fetchId (D:\Storage\Bureau\Projets\Dev\Bots\Discord\Bot\node_modules\discord.js\src\managers\MessageManager.js:135:18) {
method: 'get',
path: '/channels/785415753595486208/messages/8288745866573906',
code: 10008,
httpStatus: 404
}
In your case, collected.first() already return a Message.
If you want to fetch a message, you first need a valid id. So you need to use channelid.messages.fetch(collected.first().id); instead.
Then, you can use a catch() method to check if the message doesn't exist.
message.channel.messages.fetch(collected.first().id).then(message => console.log(message.content))
.catch(error => message.channel.send("I can't find a message with this ID"));
I'm making a bot and I have an error that I don't understand in this code : pas
const Discord = require("discord.js");
const client = new Discord.Client();
const token = "";
client.login(token)
client.on("message", async(message) => {
let staffRole = message.guild.roles.find("name", "Staff");
let staff = message.guild.member(message.author);
if (message.author.id === "424974772959444993" || message.member.roles.has(staffRole.id)) {
return;
}
var badWords = [
'asd',
'legionmods',
'verga',
'vrga',
'nmms',
'alv',
'electromods',
'remake'
];
var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
var containsBadWord = words.some(word => {
return badWords.includes(word);
});
if (containsBadWord) {
message.delete();
message.author.send({embed: {
color: 3447003,
description: `Has dicho una palabra que no esta permitida en este servidor`
}
message.channel.send(`${prefix}tempmute ${message.author}`+" 5m palabra prohibida")
}
});
This is an error I get :
(node:4952) UnhandledPromiseRejectionWarning: TypeError: Cannot read property
'roles' of null
at Client.client.on (C:\Users\Francisco\Desktop\role\app.js:8:33)
Could someone help me please ? I am not good in debugging errors.
message.guild is probably returning null because the message was sent in a dm conversation, not a guild.
You can avoid this problem by writing:
if (message.channel.type !== 'text') return;
Also, a few GuildMemberRoleManager methods have changed a bit since discord.js v12+. You should replace:
let staffRole = message.guild.roles.find("name", "Staff");
With:
let staffRole = message.guild.roles.cache.find(role => role.name === "Staff");
And replace:
message.member.roles.has(staffRole.id)
With:
message.member.roles.cache.has(staffRole.id)
I need to return a rejected promise from a js function. I am using angular $q as you can see. But it doesn't work.
In function getDBfileXHR, when the promise getDBfileXHRdeferred is rejected using getDBfileXHRdeferred.reject() I would to pass into the the error case of the function getDBfileXHR and run fallbackToLocalDBfileOrLocalStorageDB(). But it doesn't work.
Is there a syntax error ?
I am a bit new to promises.
Thanks
this.get = function () {
var debugOptionUseLocalDB = 0,
prodata = [],
serverAttempts = 0;
if (debugOptionUseLocalDB) {
return fallbackToLocalDBfileOrLocalStorageDB();
}
if (connectionStatus.f() === 'online') {
console.log("Fetching DB from the server:");
return getDBfileXHR(dbUrl(), serverAttempts)
.then(function () { // success
console.log('-basic XHR request succeeded.');
return dbReadyDeferred.promise;
}, function () { // error
console.log("-basic XHR request failed, falling back to local DB file or localStorage DB...");
return fallbackToLocalDBfileOrLocalStorageDB();
});
}
}
function getDBfileXHR(url, serverAttempts) {
var getDBfileXHRdeferred = $q.defer(),
request = new XMLHttpRequest();
if (typeof serverAttempts !== "undefined") serverAttempts++;
request.open("GET", url, true); //3rd parameter is sync/async
request.timeout = 2000;
request.onreadystatechange = function () { // Call a function when the state changes.
if ((request.readyState === 4) && (request.status === 200 || request.status === 0)) {
console.log('-we get response '+request.status+' from XHR in getDBfileXHR');
var jsonText = request.responseText.replace("callback(", "").replace(");", "");
if (jsonText === '') {
console.error('-error : request.status = ' + request.status + ', but jsonText is empty for url=' + url);
if (serverAttempts <= 2){
sendErrorEmail("BL: jsonText is empty, trying to reach server another time", 11);
getDBfileXHR(url, serverAttempts);
return;
} else {
sendErrorEmail("BL: jsonText is empty and attempted to reach server more than twice", 14);
var alertPopup = $ionicPopup.alert({
title: 'Error '+"11, jsonText is empty",
template: "Sorry for the inconvenience, a warning email has been sent to the developpers, the app is going to restart.",
buttons: [{
text:'OK',
type: 'button-light'
}]
});
getDBfileXHRdeferred.reject();
}
} else {
}
} else {
console.error('-error, onreadystatechange gives : request.status = ' + request.status);
getDBfileXHRdeferred.reject();
}
};
if (url === "proDB.jsonp") {
console.log("-Asking local proDB.json...");
} else {
console.log("-Sending XMLHttpRequest...");
}
request.send();
return getDBfileXHRdeferred.promise;
}
EDIT:
I rewrote my function using this approach. It seems better and cleaner like this. But now can you help me handle the multiple attempds ?
function getDBfileXHR(url, serverAttempts) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open("GET", url, true); request.timeout = 2000;
var rejectdum;
if (url === "proDB.jsonp") {
console.log("-Asking local proDB.json...");
} else {
console.log("-Sending XMLHttpRequest...");
}
request.onload = function () {
if ( (request.readyState === 4) && (request.status === 200 || request.status === 0) ) {
console.log('-we get response '+request.status+' from XHR in getDBfileXHR');
var jsonText = request.responseText.replace("callback(", "").replace(");", "");
if (jsonText === '') {
console.error('-error : request.status = ' + request.status + ', but jsonText is empty for url=' + url);
sendErrorEmail("BL: jsonText is empty, trying to reach server another time", 11);
sendErrorEmail("BL: jsonText is empty and attempted to reach server more than twice", 14);
var alertPopup = $ionicPopup.alert({
title: 'Error '+"11, jsonText is empty",
template: "The surfboard database could not be updated, you won't see the new models in the list, sorry for the inconvenience.",
buttons: [{
text:'OK',
type: 'button-light'
}]
});
console.log('oui on passe rejectdum')
rejectdum = 1;
reject({
status: this.status,
statusText: request.statusText
});
} else {
var parsedJson;
try {
parsedJson = JSON.parse(jsonText);
} catch (e) {
console.warn("Problem when trying to JSON.parse(jsonText) : ");
console.warn(e);
console.warn("parsedJson :");
console.warn(parsedJson);
}
if (parsedJson) {
var prodata = jsonToVarProdata(parsedJson);
console.log('-writing new prodata to localStorage');
console.log('last line of prodata:' + prodata[prodata-1]);
storageService.persist('prodata', prodata);
storageService.store('gotANewDB', 1);
}
resolve(request.response);
dbReadyDeferred.resolve();
}
}
};
request.onerror = function () {
reject({
status: this.status,
statusText: request.statusText
});
};
request.send();
});
}
Is it a clean way to do this to do several attempts :
return getDBfileXHR(dbUrl(), serverAttempts)
.then(function () { // success
console.log('-basic XHR request succeeded.');
return dbReadyDeferred.promise;
})
.catch(function (){
if (typeof serverAttempts !== "undefined") serverAttempts++;
console.log('on passe dans le catch, serverAttempts = ', serverAttempts)
if (serverAttempts < 2) {
return getDBfileXHR(dbUrl(), serverAttempts)
.then(function () { // success
console.log('-basic XHR request succeeded.');
return dbReadyDeferred.promise;
})
.catch(function (){
console.log("-basic XHR request failed, falling back to local DB file or localStorage DB...");
return fallbackToLocalDBfileOrLocalStorageDB();
})
} else {
console.log("-basic XHR request failed, falling back to local DB file or localStorage DB...");
return fallbackToLocalDBfileOrLocalStorageDB();
}
})
if you remove the code to retry (twice?) on failure your code would possibly work (haven't looked into that) -
the issue is, the only promise your calling code gets is that of the first attempt. If the first attempt fails, that promise is never resolved or rejected
You need to resolve the promise with the promise returned by getDBfileXHR(url, serverAttempts); - so, something like
if (serverAttempts <= 2){
sendErrorEmail("BL: jsonText is empty, trying to reach server another time", 11);
getDBfileXHRdeferred.resolve(getDBfileXHR(url, serverAttempts));
return;
} else {
Because if promise(1) resolves to a rejected promise(2), the result is that promise(1) rejects with the rejection value of promise(2)
This is how native Promises, and many many Promise/A+ compliant libraries work,
so this should be the case with $.defer if it follows the Promise/A+ spec
I am using ASP.NET MVC 5 for the back-end and Angular + Typescript for the front-end of a web application.
I am trying to upload a file to the server, but for some reason the controller is not getting the file as parameter (the parameter in the controller is null).
I'm sharing below code.
Thanks in advance!
HTML:
<input id="filePath" name="filePath" type="file" accept="image/*" />
<a id="uploadImage" ng-click="ctrl.uploadFile()">Upload</a>
Typescript:
// controller class:
uploadFile(): void {
var filePathInput: any = $("#filePath");
if (filePathInput[0].files) {
var file: any = filePathInput[0].files[0];
var resource: any = this.service.uploadFile();
resource.save(file, (result: any) => {
if (!result || !result.success) {
alert("error");
} else {
alert("ok");
}
});
}
}
// service class:
uploadFile(): ng.resource.IResourceClass<IMyResource> {
return this.$resource("/MyController/UploadImage", null, { method: "POST" });
}
Backend Controller:
[HttpPost]
public JsonResult UploadImage([FromBody]HttpPostedFileBase file)
{
if (file == null || file.ContentLength == 0)
{
return NullParameterResponse();
}
else
{
file.SaveAs("/img/" + Path.GetFileName(file.FileName));
return SuccessResponse();
}
}
TransformRequest function: This makes your request to be sent as a FormData instead as a JSon object.
formDataObject(data: any): any {
var fd = new FormData();
angular.forEach(data, function (value, key) {
fd.append(key, value);
});
return fd;
}
In your angular resource, define the save options and pass the transformRequest function you created earlier.
uploadChequeFile(): ng.resource.IResourceClass<IChequeLoanResource> {
return this.$resource<IChequeLoanResource>("/Cheque/UploadChequeImage", null,
{
save: {
method: "POST",
transformRequest: this.formDataObject,
headers: { 'Content-Type': undefined, enctype: 'multipart/form-data' }
}
});
}
In your controller, just call your save method from the resource passing your file.
var chequeFilePathInput: any = $("#chequeFilePath");
if (chequeFilePathInput[0].files) {
var resource: ng.resource.IResourceClass<services.IChequeLoanResource> = this.uLendService.uploadChequeFile();
resource.save({ "files": chequeFilePathInput[0].files[0] }, (result: any) => {
if (!result || !result.success) {
this.errorMessage = "Error al subir la imagen al servidor. Por favor contáctanos si el error persiste.";
} else {
this.chequeLoan.cheque.filePath = result.message;
this.saveChequeLoan();
}
});
} else {
this.errorMessage = "La imagen del cheque es requerida.";
}
Finally, your controller must receive the IList parameters (with the same name defined in your angular controller)
public JsonResult UploadChequeImage(IList<IFormFile> files)
{
try
{
if (files != null && files.Count > 0)
{
return CreateResponse(true, CreateFile(files[0], #"img\cheques"));
}
I am writing a protractor testscript for my angular js webapplication. There is a jsonfile that I am using to fill in the data on the page. The try statement will look for the element that has the model property:
var data = {name: 'James', address: '11 Sussex street'};
for (key in data) {
try {
var el = element(by.model('name'));
if (el.isElementPresent()) {
el.clear().sendKeys(data[key]);
}
}
catch (err) {
console.log('error occured', err);
}
}
When I run the test now I get an error:
TypeError: Cannot read property 'findElementsOverride' of undefined
The name element is present but does not get set?
Try this instead
var el = element(by.model('name'));
el.isPresent().then(function(present) {
if (present) {
el.clear().sendKeys('James');
}
}).catch(err) {
console.log('error occured', err);
}