In my React/Redux app, I make a call to my backend API which returns a text response. I then use the following line to retrieve the text. The issue I'm seeing is that my code seems to put two sets of quotes around the text I receive.
So, my API returns Hello World! but in the code below it becomes ""Hello World!""
My API is really returning a string so there will always be a set of quotes around the text such as "Hello World!" which is perfectly fine. I just don't understand why I'm getting two sets of quotes.
Any idea why?
export const callApi = (request) => {
return (dispatch) => fetch('/api/getsometext', fetchOptionsPost(request))
.then((response) => {
if(!response.ok) {
// Request failed
dispatch(setBadRequest(true))
} else {
const myText = response.text() // This is where I'm getting double quotes
.then((myText) => dispatch(setMyText(myText)))
}
})
}
Simply quoting #Kaiido's hint as an answer so I does not get lost in the comments:
Your server sends the data with these quotes, probably because it
thinks it should send it as JSON. So either reconfigure your API so it
doesn't try to send it as JSON, either simply use Response.JSON() so
that your client-side parses it correctly.
Related
I am using this query to edit my message's text and reply markup keyboard.
https://api.telegram.org/bot${tgBot}/editMesssageText?chat_id=${chatContext}&message_id=${originMessageID}&text=${message}&parse_mode=HTML&reply_markup={"inline_keyboard":[[{"text":"New Project","callback_data":"startInstall"}]]}
Using a URL query inspection tool, this is what I get - again, values are what they should be.
My bot token has "bot" before it in the url. The values should be exactly what they should be. I am using the correct chat_id and message_id. I am pretty sure the inline keyboard is formatted correctly. I use this same method somewhere else in my code and that works, so I'm not sure why this isn't.
For reference, this is the working method call:
https://api.telegram.org/bot${tgBot}/editMessageText?chat_id=${chatContext}&message_id=${originMessageID}&text=${message}&parse_mode=HTML&reply_markup={"inline_keyboard":${keyboardButtons}
And this is an inspection of its values. For clarification, this method is called when the user has projects in their user document, so there is supposed to be an example project in the buttons:
I have no idea what else to try at this point.
I GOT IT WORKING!!
I still am not sure EXACTLY what the root issue was, but I made a function to send these requests as I wanted to make sure I wasn't misspelling something simple and it just started working.
In case anyone runs into this same issue, this was my function.
async function editMessage(botToken: string, chatId, messageId, text: string, parseMode, replyMarkup) {
if (replyMarkup == undefined) {
const res = await fetch(
`https://api.telegram.org/bot${botToken}/editMessageText?chat_id=${chatId}&message_id=${messageId}&text=${text}&parse_mode=${parseMode}`
)
return res
} else {
const res = await fetch(
`https://api.telegram.org/bot${botToken}/editMessageText?chat_id=${chatId}&message_id=${messageId}&text=${text}&parse_mode=${parseMode}&reply_markup=${replyMarkup}`
)
return res
}
}
I'm making a Discord bot in JavaScript and implementing a feature where when you ask a coding question it gives you a snippet. I'm using Grepper and returning the url with the search results. For example:
Hello World in JavaScript Search Results. I would like to access the div containing the snippet. Is this possible? And how would I do it?
Here's my code:
if (message.startsWith('programming')) {
// Command = programming
message = message.replace('programming ', ''); // Remove programming from the string
message = encodeURIComponent(message) // Encode the string for a url
msg.channel.send(`https://www.codegrepper.com/search.php?answer_removed=1&q=${message}`); // Place formatted string into url and send it to the discord server
// Here the program should access the element containing the snippet instead of sending the url:
}
I'm new to JavaScript so sorry if this is a stupid question.
As far as I know the API you are using returns HTML/Text data, not JSON, Grepper has a lot more APIs if you just look into them, you can instead use this API that returns JSON data. If you need more information you can check this Unofficial List of Grepper APIs
https://www.codegrepper.com/api/get_answers_1.php?v=2&s=${SearchQuery}&u=98467
How Do I Access the div containing the snippet?
To access the div you might need to use python web scraping to scrape the innerHTML of the div but I think it's easier to use the other API.
Or
You can put /api/ in the url like:
https://www.codegrepper.com/api/search.php?answer_removed=1&q=js%20loop
The easiest way for this is to send a GET request to the underlying API
https://www.codegrepper.com/api/search.php?q=hello%20world%20javascript&search_options=search_titles
This will return the answers in JSON format. Obviously you'd have to adjust the parameters.
How did I find out about this?
Simply look at the network tab of your browser's dev tools while loading the page. You'll see a GET request being sent out to the endpoint, returning mentioned answers as JSON.
The best way is to use the grepper api.
Install node-fetch
npm i node-fetch, You need this package for making requestes to the api.
To import It in the code just type:
const fetch = require('node-fetch');
Write this code
Modify your code like this:
if (message.startsWith('programming')) {
message = message.replace('programming ', '');
message = encodeURIComponent(message)
// Making the request
fetch(`https://www.codegrepper.com/api/search.php?answer_removed=1&q=${message}`)
.then(res => res.json())
.then(response => {
// response is a json object containing all the data You need
// now You need to parse this data
const answers = response.answers; // this is an array of objects
const answers_limit = 3; // set a limit for the answers
// cheking if there is any answer
if(answers.length == 0) {
return msg.channel.send("No answers were found!");
}
// creating the embed
const embed = new Discord.MessageEmbed()
.setTitle("Here the answers to your question!")
.setDescription("")
// parsing
for(let i = 0; i < answers_limit; i++) {
if(answers[i]) {
embed.description += `**${i+1}° answer**:\n\`\`\`js\n${answers[i].answer}\`\`\`\n`;
}
}
console.log(embed)
msg.channel.send(embed);
});
}
My current NuxtJS Application contains the following code:
// Create a new Canvas-Object on a Whiteboard
async createCanvasObject({ state }, canvasObject) {
if (!state.id) {
console.error(' Canvas ID is not defined!');
return;
}
console.log(canvasObject);
console.log(canvasObject.mtiID);
await this.$axios
.$post(`/whiteboard/${state.id}/canvas/object`, {
object: canvasObject,
})
.then((res) => console.log(res));
},
What should this code do?
It should send a passed object canvasObject via POST-Request to my backend, without modifying it.
The canvasObject itself is a JSON-Object, which describes an Object on a Canvas.
The logging directly before the Axios-Call yields something like this:
As you can see, there is a lot of stuff defined, and espacially the attribute mtiID.
Now the Problem:
If we look at the request, we can see, that a lot of stuff got stripped away from my JSON, including the mtiID. I have no idea why. The only 'Middleware', that is currently applied to Axios just logs every request to the console, without modifying it.
So the code I'm trying to send is ( "buyPrice":11.0 ). on the site (https://api.hypixel.net/skyblock/bazaar/product?key=a8394dae-033b-4ce5-a1a1-fb773cf2386f&productId=PORK).
As you can see, the value inside the buyPrice is not a string but a number.
And now, when I send the command into discord, it says "undefined".
But when I saw a code bellow that is valued is a string of the same website ("warning": "This endpoint is deprecated and will soon be disabled.").
It worked flawlessly, so I'm thinking.
.toString()
but I don't know where I am going to put the code in
my code is:
} else if (command === "bazaar") {
let getBazaar = async () => {
let response = await axios.get(
'https://api.hypixel.net/skyblock/bazaar/product?key=a8394dae-033b-4ce5-a1a1-fb773cf2386f&productId=PORK'
);
let bazaar = response.data;
return bazaar;
};
let bazaarValue = await getBazaar();
console.log(bazaarValue)
message.channel.send(`Buy Price: ${bazaarValue.buyPrice}`)
This doesn't seem to be an error in your code. Just a legitimate warning from the API host stating that the url you are using (https://api.hypixel.net/skyblock/bazaar/product?key=a8394dae-033b-4ce5-a1a1-fb773cf2386f&productId=PORK) will be disabled.
As you mentioned where you are trying to send ("buyPrice": 11.0), do read the comment by ippi, you need to see the json that the API is returning and find the value properly.
As for the message send command, (`Buy Price: ${bazaarValue.buyPrice}`) will always be a string, no matter what type bazaarValue.buyPrice is.
I have the following in my typescript file
async createProduct(data) {
return await axios.post(request).catch(error => {
console.log('error'.bgRed.white.bold, error)
});
}
that error looks like this when logged
I need to single out the error from the outside api which looks like this
How do I single out that part like any other object ie return error.title
Update
here is the full response https://jsoneditoronline.org/#left=cloud.c584e42736664e9595fcfd8bb9c668a4
Try const errorObject = JSON.parse(error.config.data).
If the syntax in the string is correct, you should be able to access the title as usual errorObject.title