I'm working on my Project and currently I have one API call to spoonacular's search by recipe GET request. I want to add the search by video GET Request but I seem to having problems getting both to render at once into the DOM. How can I fix this issue?
const apikey = '';
const urls = { search:'https://api.spoonacular.com/recipes/complexSearch',
videos: 'https://api.spoonacular.com/food/videos/search'
};
function queryParams(params) {
const queryItems = Object.keys(params).map(key=>`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
return queryItems.join('&');
}
///render results
function getRecipe(tacos,maxResults){
const params ={
query: tacos,
number: maxResults,
};
const queryString = queryParams(params)
const url = urls+'?'+queryString +'&apiKey='+ apikey;
console.log(url);
fetch(url)
fetch(urls.search)
.then(response =>{
if(response.ok){
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson))
.catch(err =>{
$('#js-error-message').text(`Something went wrong: ${err.message}`);
});
}
Your urls is an object containing two strings. You need to treat it as such and make two separate calls.
You should have a fetch(urls.search) and fetch(urls.videos) call, each with their own response chain.
I'm not sure this code is doing what you think it is:
const url = urls+'?'+queryString +'&apiKey='+ apikey;
You'll need to append the queryString and apiKey to each string within urls separately. Something like
const searchUrl = urls.search+'?'+queryString +'&apiKey='+ apikey;
const videosUrl = urls.videos+'?'+queryString +'&apiKey='+ apikey;
Related
I am using Local Storage for my login page
but my variables not storing in the local storage I don't know why....
I am using the following code on my button click....
But the APi i am using is correct... It works fine
res.data.status gives true or false,Inside Axios .then => If is used for correct username and password and else is used for incorrct user
This is my Code:
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}
if your variable is not stored in the localStorage. that's because of the condition you have. also as you're sure that your API is working fine and you can successfully make a request and receive a response. then the issue is with the condition. because from your code. you're making conditions only if the request is not successful. you don't have the condition for success.
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){ <= remove the !
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}
At the end of the waterfall-dialog in "summary" (i.e., the last if statement) i want to automatically make a post request without making an API call in Postman, is eventListener the way? How to include it?
async summaryStep(step) {
if (step.result) {
// Get the current profile object from user state.
const userProfile = await this.userProfile.get(step.context, new UserProfile());
userProfile.name = step.values.name;
//the same for other step values(email, doctor, date)
let msg = `you want a date with dr. ${userProfile.doctor} , and your name is ${userProfile.name}.`;
if (userProfile.date !== -1) {
msg += `you have an appointment the: ${userProfile.date}.`;
}
await step.context.sendActivity(msg);
let msg1 = `"${userProfile.date}"`;
if (msg1) {
let z = JSON.stringify(userProfile.name);
//and also the other rows to go in the database(email, doctor, date)
var name = JSON.parse(z);
//and also the other rows to go in the database(email, doctor, date)
//this actually works but only if i use postman
var urlencoded = bodyparser.urlencoded({ extended: false });
app.post('/id', urlencoded, (req, res) => {
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mysqlConnection.query("INSERT INTO users(name, email, doctor, date) VALUES('" + userProfile.name + "','" + userProfile.password + "','" + userProfile.doctor + "','" + userProfile.date + "')", function (err, result, rows) {
if (err) throw err;
console.log("Yeah! record inserted");
console.log(name);
res.send(result);
});
});
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));
}
} else {
await step.context.sendActivity('Thanks. Your profile will not be kept. Push enter to return Menu');
}
return await step.prompt(CONFIRM_PROMPT3, `is that true? ${step.result}`, ['yes', 'no']);
// this if statement should "fire" the post request...
if (step.result == 'yes') {
return await step.context.sendActivity(`we will contact you soon ${userProfile.password}.`);
}
return await step.endDialog();
}
Per my understanding , you want to know how to call an POST API from Azure bot async function. Pls try the code below in your async summaryStep function to send the post request based on your requirement.
var rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://localhost:8080/id',
body: {
fieldCount:0,
affectedRows:1,
//your other body content here...
},
json: true,
headers: {
'content-type': 'application/json' //you can append other headers here
}
};
await rp(options)
.then(function (body) {
console.log(body)
})
.catch(function (err) {
console.log(err)
});
}
Hope it helps .
A
nd if there is any further concerns or misunderstand , pls feel free to let me know.
The answer is to move your app.post API endpoint to your index.js file where your bot is already running on a server. Simply spin up a new "server" and "port" making the endpoint available. Then, in your summaryStep (axiosStep in my example), make your API call using Axios, request-promise, or what have you, to post your data. When the API is hit, the data will be passed in and processed.
In the code below, when the API is hit the passed in data is used in a sendActivity posted back to the bot. In your case, your passed in data would be used for the database call in which you could use the returned response in the sendActivity.
Your code would look something like the following. Please note, the post actions are simplified for the sake of the example. You would need to update the post actions to make your mySql queries. This sample also makes use of restify for the server (standard for Bot Framework bots) and uses the same port as the bot, but this can easily be updated to use Express and/or another port.
Hope of help!
index.js
[...]
const conversationReferences = {};
const bodyParser = require('body-parser');
server.post('/id', async (req, res) => {
const { conversationID, data, name } = req.body;
const conversationReference = conversationReferences[ conversationID ];
await adapter.continueConversation(conversationReference, async turnContext => {
var reply = `${ data }. Thanks, ${ name }`;
await turnContext.sendActivity(reply);
});
res.writeHead(200);
res.end();
});
mainDialog.js
async axiosStep ( stepContext ) {
const conversationID = stepContext.context.activity.conversation.id;
try {
const response = await axios.post(`http://localhost:3978/id`, {
data: "Yeah! Record inserted",
name: "Steve",
conversationID: conversationID
})
console.log(response);
} catch (error) {
console.log(error);
}
return stepContext.next();
}
I am trying to change the required engine version of an AppPackage that I have posted using v2 of the Design Automation API.
I've tried using Postman and the Forge Node Client. I'm using the Forge documentation as a reference.
https://forge.autodesk.com/en/docs/design-automation/v2/reference/http/AppPackages(':id')-PATCH/
My credentials are correct and I have a valid token, but for some reason I keep getting a 404 Not Found status and an error that says "AppPackage with the name MyPlugin doesn't belong to you. You cannot operate on AppPackage you do not own." Also, I get the same message when I try to delete or update the AppPackage.
That's really weird because I definitely own this AppPackage. I uploaded it with these same credentials and I can view it by doing a GET request to view all of my AppPackages. Furthermore, the name of the AppPackage is correct and I specified the right scope (code:all) when I authenticated.
Why does Design Automation think this AppPackage doesn't belong to me and why can't I patch, update, or delete it?
UPDATE 3/28/2019: Setting the resource value still results in the same error
UPDATE 4/2/2019: Getting a fresh upload URL doesn't work either. I get an internal server error saying "Object reference not set to an instance of an object."
const ForgeSDK = require('forge-apis');
const oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, SCOPES);
const appPackageApi = new ForgeSDK.AppPackagesApi();
const getToken = () => {
return oAuth2TwoLegged.authenticate();
};
const getUploadURL = () => {
return appPackageApi.getUploadUrl(oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};
const patchPackage = (id, url) => {
const appPack = {
Resource: url,
RequiredEngineVersion: APP_PACKAGE_REQUIRED_ENGINE
};
return appPackageApi.patchAppPackage(id, appPack, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};
(async () => {
try {
const token = await getToken();
const url = await getUploadURL();
const patchPackRes = await patchPackage(APP_PACKAGE_ID, url);
if (patchPackRes.statusCode == 201)
console.log('Patch package succeeded!');
else
console.log('Patch package failed!' + patchPackRes.statusCode);
} catch (ex) {
console.log('Exception :(');
console.log(ex);
}
})();
When calling PATCH the "Resource" property must be set. It can be set to the same URL as the one you receive from GET but it must be present and valid.
This should work:
const ForgeSDK = require('forge-apis');
const oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, SCOPES);
const appPackageApi = new ForgeSDK.AppPackagesApi();
const getToken = () => {
return oAuth2TwoLegged.authenticate();
};
const getUploadURL = async (id) => {
const app = await appPackageApi.getAppPackage(id, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
return app.body.Resource;
};
const patchPackage = (id, url) => {
const appPack = {
Resource: url,
RequiredEngineVersion: APP_PACKAGE_REQUIRED_ENGINE
};
return appPackageApi.patchAppPackage(id, appPack, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};
(async () => {
try {
const token = await getToken();
const url = await getUploadURL(APP_PACKAGE_ID);
const patchPackRes = await patchPackage(APP_PACKAGE_ID, url);
if (patchPackRes.statusCode == 201)
console.log('Patch package succeeded!');
else
console.log('Patch package failed!' + patchPackRes.statusCode);
} catch (ex) {
console.log('Exception :(');
console.log(ex);
}
})();
What's wrong with this picture ? :-)
I'm trying to pull values from my wordpress JSON objects.
I must not be addressing them the correct/proper way with React-Native.
Can someone direct me as to how to form the correct console log statement ?
As it stands right now, the variable 'theMediaLink' is coming up 'undefined' in the console log. :-(
state={
data:[]
}
fetchData = async() => {
const response = await
//response
fetch('http://example.com/wp-json/wp/v2/posts/')
//posts
const posts = await response.json();
this.setState({data:posts});
const theMediaLink = `https://example.com/wp-json/wp/v2/media/` + `${this.state.data.featuredmedia}`;
console.log('theMediaLink_value: ', theMediaLink);
}
I should add that the fetch is retrieving data as I use it later on with a FLATLIST to pull the posts. My question is I must be misforming the call, but how ?
This is more an issue of understanding of React rather than React Native.
Try this:
fetchData = async () => {
const URL = 'http://example.com/wp-json/wp/v2/posts/'
const response = await fetch(URL)
const posts = await response.json();
return this.setState({ data : posts }, () => {
const { data } = this.state
const theMediaLink = `https://example.com/wp-json/wp/v2/media/${ data.featuredmedia }`;
console.log('theMediaLink_value: ', theMediaLink);
});
}
Since setState is asynchronous, you won't be able to see the state update right away, that's why the callback is for.
More info on how to setState asynchronously and use its value after right here
I would like to scrape this page: calendar events
for specific data, like formattedDate and description. How do I go about that in a module in Node.JS. I am having a hard time understanding the process in Node.JS.
Any help would go a long way, thanks in advance.
it's pretty simple, you can import the request module and use it. For example, see code below.
const request = require("request");
request("MY_URL", (error, response, body) => {
console.log('body:', body);
});
Also, you can try this here, on Repl.it
First of all, you need to parse your JSON, this allows you to access fields from received json.
const data = JSON.parse(body);
Now, if you want to access some information about an event you need to loop events and access what you need, something like:
const events = data.bwEventList.events;
events.map((data, index) => console.log(data.calendar))
Final code also on Repl.it
from nodeJS docs here
const http = require('http');
http.get('http://umd.bwcs-hosting.com/feeder/main/eventsFeed.do?f=y&sort=dtstart.utc:asc&fexpr=(categories.href!=%22/public/.bedework/categories/sys/Ongoing%22%20and%20categories.href!=%22/public/.bedework/categories/Campus%20Bulletin%20Board%22)%20and%20(entity_type=%22event%22%7Centity_type=%22todo%22)&skinName=list-json&count=30', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData["bwEventList"]["resultSize"]);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
see console.log(parsedData["bwEventList"]["resultSize"]);
slice parsedData as an array until you get what you want