I want to send data about shopping cart from mongoDB to front-end page, use I use Koa and EJS engine, and I sure I have successfully get data from database. But in web page, it shown undefined
router.get('/cart', loadCart)
async function loadCart(ctx){
let userid = ctx.session.userID
let c_data = await C.getCart(userid)
console.log(typeof(c_data))
await ctx.render('cart',{
userid, c_data
})
}
code in html
<input type="hidden" value="<%= c_data %>" id="data">
function loadCart(){
let content = ""
let c_data = document.getElementById('data').value
c_data.forEach(element => {
console.log(element.name)
});
}
Did you add render settings like bellow?
render(app, {
root: templatesPath,
layout: 'template',
viewExt: 'html',
cache: false,
debug: false,
async: true
})
I think two properties here are important: root and layout.
Related
I am trying to create a site using data fetched from a directus instance.
Currently I have a layout component app.vue filling all seo meta tags using static default values hardcoded in that file.
So in the setup I am using:
useSeoMeta({
title: () => "Static title"
})
which is not creating the desired output. No title is rendered.
Also for a post component I want to overwrite the values from layout using data fetched from a remote source:
const { data: post, pending } = await useAsyncData('post', () => {
return getItemById({
collection: "collection_id",
filter: {
status: "published"
},
id: route.params.id,
}).then((data) => {
let ast = Markdoc.parse(data.content);
let transform = Markdoc.transform(ast);
data.content = Markdoc.renderers.html(transform);
useSeoMeta({
title: data.seo_title,
});
return data;
});
});
This is also not working as expected and serves different result, depending weather ssr is applied or not.
How would one implement a solution like this?
I am having issues with sending files to the endpoint: https://developer.api.autodesk.com/photo-to-3d/v1/file
Once I receive the Auth token, I successfully create a Photo Scene with: https://developer.api.autodesk.com/photo-to-3d/v1/photoscene.
Then I also check, if the Photo scene is indeed created by calling the: https://developer.api.autodesk.com/photo-to-3d/v1/photoscene/${photosceneid}/properties.
If that goes through, I send the image files, which I first upload to a storage server
(because sending the files directly didnt work) and then I run:
let image_urls = await temporary_image_upload(files, photosceneid)
const form_data = new FormData();
form_data.append("photosceneid", photosceneid)
form_data.append("type", "image")
image_urls.forEach(url => form_data.append("file", url))
// I also tried:
// image_urls.forEach((url, index) => form_data.append(`file[${index}]`, url))
// Upload photos
const { data } = await axios.post(
"https://developer.api.autodesk.com/photo-to-3d/v1/file",
form_data,
{ headers }
)
//
//
// I also tried adding it as query params:
image_urls = image_urls.map((url, index) => `file[${index}]=${url}`).join("&")
// Upload photos
const { data } = await axios.post(
"https://developer.api.autodesk.com/photo-to-3d/v1/file",
`photosceneid=${photosceneid}&type=image&${image_urls}`,
{ headers }
)
But nothing seems to work and I get response:
{
Usage: '0.47925591468811',
Resource: '/file',
Error: {
code: '19',
msg: "Specified Photoscene ID doesn't exist in the database"
}
}
So I am not sure what might be wrong, since I can clearly verify that the Photo Scene has been created.
Could you please provide some support, been struggling with this for a few days now.
As you mentioned you can clearly confirm the photosceneid exists, I would suspect that your axios request is not as expected, maybe add details about your header. Here is a sample:
Axios({
method: 'POST',
url: 'https://developer.api.autodesk.com/photo-to-3d/v1/file',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + access_token
},
data: querystring.stringify({
photosceneid: photosceneId,
type: 'image',
'file[0]': 'https://path/to/file.JPG'
})
})
I'm doing the wikipedia viewer from FCC projects with React, Im trying to make the request by just passing it the searchQuery (from my state) with template string. Like this:
gettingArticle() {
const { searchQuery, articlesList } = this.state;
const API = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
const body = { method: 'GET', dataType: 'json'};
const myRequest = new Request(API, body);
fetch(myRequest)
.then(response => response.json())
.then(data => this.setState({
articlesList: data, articles: true }));
console.log( 'data fetched' + displayedArticles);
}
I don't know for sure if is like this that I have to made the request it's just what I saw on the docs. I want to made the request and after receive the data I want to iterate over the array of objects and put every little thing that I need in their corresponding tag inside a div. Here is my entire code: https://codepen.io/manAbl/pen/VxQQyJ?editors=0110
The issue is because you missed a key details in the API documentation
https://www.mediawiki.org/wiki/API:Cross-site_requests
Unauthenticated CORS requests may be made from any origin by setting the "origin" request parameter to "*". In this case MediaWiki will include the Access-Control-Allow-Credentials: false header in the response and will process the request as if logged out (in case credentials are somehow sent anyway).
So I update your url like below
const API = `https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
And also your console.log was at the wrong place, so I changed it to below
fetch(myRequest)
.then(response => response.json())
.then(data => {
console.log( 'data fetched', data);
this.setState({
articlesList: data, articles: true })
});
Below is a updates pen
https://codepen.io/anon/pen/BxMyxX?editors=0110
And now you can see the API call works
Of course I didn't check why you have white strip after the call is successful, but that may be something wrong you do in your React code
The problem is not really in your code but in CORS, basically you are not allowed to make the call because of same origin policy.
Change these 2 constants
const API = `https://crossorigin.me/https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
const body = { method: 'GET', dataType: 'json', mode: 'cors', cache: 'default'};
I added crossorigin url before your API because it 'overrides' CORS and enables you to make calls outside the same origin policy. You should also modify your submit function:
handleSubmit(ev) {
ev.preventDefault(); //This disables default form function (reload/redirect of website and loss of state)
this.gettingArticle();
}
This is the view, the success function should make changes in the <p id="mondiv"></p>tags.
<input type="button" value="Refuser" class="refuser" id="{{ demande.id }}">
<p id="mondiv"></p>
<script>
$(".refuser").click(function () {
$.ajax({
url: '{{ path('verifier_demandes') }}',
type: 'POST',
data: {'id_demande': this.id},
dataType: 'json',
success: function (data) {
$.each(data,function (i,e) {
$('#mondiv').append('<ul>'
+'<li>'+e.id+'</li>'
+'<li>'+e.etat+'</li>'
+'<li>'+e.user.nom+'</li>'
+'<li>'+e.user.prenom+'</li>'
+'<li>'+e.user.username+'</li>'
+'</ul>');
})
},
error: function(data) {
alert('error');
}
})
}
);
This is the controller, the entity gets deleted like intended but since then i can't change my view element ( the success function )
if($request->isXmlHttpRequest())
{
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
$gerant = new Gerant();
$gerant = $em->getRepository("GestionBoutiquesBundle:Gerant")->findOneBy(array('id' => $id_gerant));
$em->remove($gerant);
$em->flush();
$demandes = new Gerant();
$demandes=$em->getRepository('GestionBoutiquesBundle:Gerant')->findBy(array('etat'=>false));
$ser= new Serializer(array(new ObjectNormalizer()));
$data=$ser->normalize($demandes);
return new JsonResponse($data);
}
}
I have looked from both sides, the controller sending back the Json response, and from the view, but couldn't find any result.
EDIT: knowing that the $demandes i'm trying to send back with Json is an array of users, each user has an id, etat, nom, prenom, username..
You made a POST request so you should be able to access to the post data as follow:
$id_gerant = $request->request->get('id_demande');
if($id_gerant) {
....
instead of:
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
....
As described here in the doc Symfony Request Object
Hope this help
The problem I have is that my application works when I submit only one 1 when I press the Submit button multiple times it freezes and after some time (about 1000.000 ms) it returns the last request in the console and jade page. The submit button returns a post from the form and sends it to the same page . What the button also does is Refreshing the page. It is important that the page returns the (JSON) post to the page and there is an other json request that sends it to the API(and returns it to the same page )
app.js
var options_search = {
hostname: 'host',
path: 'path',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': JSON request .length,
}
};
app.post('/result',function(req,response){
var keyword=req.body.user;
GLOBAL.objToJson ={ keyword };
response.write(JSON.stringify(GLOBAL.objToJson));
console.log("test " +JSON.stringify(GLOBAL.objToJson) );
});
app.get('/Search', function(req, res) {
var req = http.request(options_search, (resb) => {
var buffer_search = "";
resb.setEncoding('utf8');
resb.on('data', (chunks) => {
buffer_search += chunks;
});
resb.on('end', () => {
res.render('Search',{
title: 'Search',
value_search: buffer_search,
search_test: [JSON.stringify(GLOBAL.objToJson) ]
});
});
});
//res.redirect("/search");
req.write(search);
});
search.jade
doctype html
html
head
script(src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js')
script.
$(document).ready(function(){
var user,pass;
$("#submit").click(function(){
user=$("#user").val();
pass=$("#password").val();
$.post("http://localhost:3000/result",{user: user}, function(data){
if(data==='done')
{
alert("login success");
}
});
});
});
input#user(type='TEXT', size='40')
br
input#submit(type='button', value='Submit',onclick="location.href='search'")
In the result route you are using the underlying HTTP .write() method to respond to the client. However this does not end the connection, which will stay open expecting more things to be written to the client.
If you are sending a string you should use .send() as that will write the string to the HTTP stream and end the response.
You may also want to consider not stringifying the object to a JSON string and just using .json() instead. So the line of code
response.write(JSON.stringify(GLOBAL.objToJson));
becomes
response.json(GLOBAL.objToJson);