Nuxt.js + Vue.js + Javascript Hackernews API displaying comments (nested kids also) - javascript

I have following code in my project:
<template>
<div>
<Head>
<Title>{{ story.title}}</Title>
<Meta name="description" content="product.description" />
</Head>
<StoryDetails :story="story" />
<button class="btn">
<NuxtLink to="/">Back to home</NuxtLink>
</button>
</div>
</template>
scripts:
<script setup>
definePageMeta({
layout: "stories"
})
const { id } = useRoute().params
const uri = 'https://hacker-news.firebaseio.com/v0/item/'+ id +'.json?print=pretty'
const { data: story } = await useFetch(uri, { key:id })
const { data: comments} = []
if(!this.story.value) {
throw createError({ statusCode: 404, statusMessage: 'Story not found!', fatal: true })
}
this.story.kids.forEach(id => {
$fetch('https://hacker-news.firebaseio.com/v0/item/'+ id +'.json?print=pretty')
.then((response) => {
this.comments.push(response)
console.log(this.comments)
})
.catch(err=> {q
this.err = err
})
})
console.log(this.comments)
</script>
Please, help. How can I display comments (nested kids also) ?
I am getting this error for code above:
GET http://localhost:3000/_nuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css net::ERR_ABORTED 404 (Page not found: /_nuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css)
My github repo: https://github.com/AzizxonZufarov/newsnuxt2/blob/main/pages/%5Bid%5D.vue
PS: Also I am getting this error:
[plugin:vite:css] [postcss] C:/Users/Acer/Desktop/newsnuxt/pages/[id].vue?vue&type=style&index=0&scoped=dd4001d8&lang.css:4:15: Unknown word
C:/Users/Acer/Desktop/newsnuxt/pages/[id].vue:4:15
2 | <div>
3 | <Head>
4 | <Title>{{ story.title}}</Title>
| ^
5 | <Meta name="description" content="product.description" />
6 | </Head>

Related

Get elements from JSON array to display as a text

So i am trying to get a first_name from JSON object which has array of elements by iterating through it, for example if i type 'Ron' it will display as a text but for some reason I can't get display it as a text unless i send in a respond this `
playerName: nbaPlayer[0]
But it only displays one element as a text since others are not in a response
reponse in a server enter image description here
Here is a code for fetch where i use search bar from handlebars to search for a first_name
const nbaForm = document.querySelector('form')
const search = document.querySelector('input')
const messageOne = document.querySelector('#player-1')
nbaForm.addEventListener('submit', (event) => {
event.preventDefault()
const playerSearch = search.value
messageOne.textContent = 'Loading...'
fetch('http://localhost:4000/nba').then((response) => {
response.json().then(nbaData => {
if (nbaData.playerName === playerSearch) {
messageOne.textContent = nbaData.playerName
} else {
messageOne.textContent = 'not found'
}
})
})
})
request method
app.get('/nba', (req,res) => {
networkManager.nbaPlayerData((data)=>{
/
var nbaPlayer = []
for(var i=0; i<data.data.length; i++){
nbaPlayer.push(data.data[i].first_name)
}
console.log(nbaPlayer)
res.send({
playerName: nbaPlayer
})
})
})
handlebars file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NBA</title>
<link rel = "stylesheet" href="/css/style.css">
</head>
<body>
<div class="main-content">
<h1>NBA SERVER</h1>
<p>Use this site to get NBA player</p>
<form action="">
<input placeholder="Type a players name">
<button>Search</button>
</form>
<p id="player-1"></p>
<h1>{{playerName}}</h1>
</div>
<script src ="/js/fetch-app.js"></script>
</body>
</html>
try this.
fetch('http://localhost:4000/nba').then((response) => {
response.json().then(nbaData => {
var index = nbaData.playerName.indexOf(playerSearch)
if (index !== -1) {
messageOne.textContent = nbaData.playerName[index]
} else {
messageOne.textContent = 'not found'
}
})
})
You are getting an array from
res.send({
playerName: nbaPlayer // nbaPlayer is array
})
but in your fetch, you want to get data as from simple object

Uncaught TypeError in javascript

I have created chatbot using pytorch and integrating it into flask project.
But getting some erros please help me with it. Thanks!
// app.js
app.js file used while creating chatbot
class Chatbox {
constructor() {
this.args = {
openButton : document.querySelector('.chatbox__button'),
closeButton : document.querySelector('.chatbox__support'),
sendButton : document.querySelector('.send__button')
}
this.state = false;
this.messages = [];
}
display() {
const {openButton, chatBox, sendButton} = this.args;
openButton.addEventListener('click', () => this.toggleState(chatBox))
sendButton.addEventListener('click', ()=> this.onSendButton(chatBox))
const node = chatBox.querySelector('input');
node.addEventListener("keyup", ({key}) => {
if (key === "Enter"){
this.onSendButton(chatBox)
}
})
}
toggleState(chatBox){
this.state = !this.state;
if(this.state){
chatBox.classList.add('chatbox--active')
}else{
chatBox.classList.remove('chatbox--active')
}
}
onSendButton(chatbox){
var textField = Chatbox.querySelector('input');
let text1 = textField.value
if (text1 === ""){
return;
}
let msg1 = {name : "User", message:text1}
this.messages.push(msg1);
fetch($SCRIPT_ROOT + '/predict', {
method: 'POST',
body : JSON.stringify({message:text1}),
mode : 'cors',
headers : {
'Content-Type' : 'application/json'
},
})
.then(r => r.json())
.then(r => {
let msg2 = {name: 'Sam', message: r.answer};
this.messages.push(msg2);
this.updateChatText(chatbox)
textField.value = ''
}).catch((error) => {
console.error('Error:', error);
this.updateChatText(chatbox)
textField.value = ''
});
}
updateChatText(chatbox){
var html = '';
this.messages.slice().reverse().forEach(function(item,){
if (item.name === 'Sam'){
html += '<div class="messages__item messages__item--visitor'> + item.message + '<div>'
}
else{
html += 'div class="messages-__item messages__item--operator' + item.message + '<div>'
}
});
const chatmessage = chatbox.querySelector('.chatbox__messages');
chatmessage.innerHTML = html;
}
}
const newChat = new Chatbox();
newChat.display();
base.html
frontend file to render chatbot window. But on clicking on icon it does not loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chatbot</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div class="container">
<div class="chatbox">
<div class="chatbox__support">
<div class="chatbox__header">
<div class="chatbox__image--header">
<img src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png" alt="image">
</div>
<div class="chatbox__content--header">
<h4 class="chatbox__heading--header">Chat support</h4>
<p class="chatbox__description--header">Hi. My name is Sam. How can I help you?</p>
</div>
</div>
<div class="chatbox__messages">
<div></div>
</div>
<div class="chatbox__footer">
<input name="input" type="text" placeholder="Write a message...">
<button class="chatbox__send--footer send__button">Send</button>
</div>
</div>
<div class="chatbox__button">
<button><img src="{{ url_for('static', filename='images/chatbox-icon.svg') }}" /></button>
</div>
</div>
</div>
</body>
<script>
$SCRIPT_ROOT = {{ request.script_root|tojson }};
</script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
</html>
Im getting the following errors:
Uncaught TypeError: Cannot read properties of undefined (reading 'querySelector')
at Chatbox.display (app.js:20:34)
at app.js:95:9
app.js:33 Uncaught TypeError: Cannot read properties of undefined (reading 'classList')
at Chatbox.toggleState (app.js:33:25)
at HTMLDivElement.<anonymous> (app.js:16:61)
Python chatbot using Pytorch
Error 1: chatBox is undefined because this.args does't have the chatBox property, you wrote "closeButton" at the 2nd position.
Erorr 2: Again, chatBox is undefined.

inline javascript callback onclick using mustache templating

Screenshot of UI
I'm having an issue invoking the inline javascript inside the mustache template file (.hjs).
when I click "Verify", the script tag and console logs do not run. It is not pulling the input code I type into the input box either.
For context: I am sending the mustache template (html) from my node server to an iFrame on the front end (React). I want the template to interact with the user and send an API call to my server and verify the 2FA.
I am sending variables to the javascript through {{ var }}, which is standard for mustache.
My thoughts: this code works in a regular index.html file.
any help or tips appreciated! I can try any suggestions locally to debug further.
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div id="inline-widget" style="margin:0 auto;width: 360px;padding:5px">
<p style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#48545d;font-size:14px;line-height:125%;margin:10px auto 20px;text-align:center">
Please complete your purchase by entering the 4 character code at the end of your recent charge description.
</p>
<img style="width: 350px;text-align:center;border:1px solid black" src="https://d2xxy1rwbjzckp.cloudfront.net/verification.jpeg" alt="Example"></img>
<p style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#48545d;font-size:11px;line-height:125%;margin-bottom:10px auto 20px;text-align:left">
Code = 3122 in this example
</p>
<p id="error-message" style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#48545d;font-size:11px;line-height:125%;margin-bottom:10px auto 20px;text-align:center;color:red"></p>
<div class="input-group mb-3">
<input id="2faCode" type="text" class="form-control" placeholder="4 digit code" aria-describedby="basic-addon2"/>
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="verifyButton" type="button">Verify</button>
</div>
</div>
</div>
<script>
const button = document.getElementById('verifyButton');
button.addEventListener('click', async _ => {
try {
const verifyCode = document.getElementById('2faCode').value;
console.log('start!: ', verifyCode);
const response = await fetch({{ callbackUrl }}, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
orderId: {{ orderId }},
verificationCode: {{ verifyCode }}
})
});
const contentType = response.headers.get("content-type");
if (contentType === 'text/html; charset=utf-8') {
const textResponse = await response.text();
document.getElementById("inline-widget").innerHTML = textResponse;
} else {
const parsedResponse = await response.json();
document.getElementById("error-message").innerHTML = parsedResponse.message;
}
} catch(err) {
document.getElementById("error-message").innerHTML = err;
console.error(`Error: ${err}`);
}
});
</script>
</body>
</html>

Trying to add a 2 character state code to my National Parks project

In my search, when I add states such as Michigan or Ohio it returns back National State Parks this part works fine. My problem is that when you just add the State abbreviation it doesn't work so well.
In the API documentation, I can add 'stateCode A comma delimited list of 2 character state codes.' at which I have. In turn it spits out a CURL at which I am not familiar with at all. This is the curl: curl -X GET "https://developer.nps.gov/api/v1/parks?stateCode=AK%2C%20AL%2C%20AR%2C%20AZ%2C%20CA%2C%20CO%2C%20CT%2C%20DC%2C%20DE%2C%20FL%2C%20GA%2C%20HI%2C%20IA%2C%20ID%2C%20IL%2C%20IN%2C%20KS%2C%20KY%2C%20LA%2C%20MA%2C%20MD%2C%20ME%2C%20MI%2C%20MN%2C%20MO%2C%20MS%2C%20MT%2C%20NC%2C%20ND%2C%20NE%2C%20NH%2C%20NJ%2C%20NM%2C%20NV%2C%20NY%2C%20OH%2C%20OK%2C%20OR%2C%20PA%2C%20RI%2C%20SC%2C%20SD%2C%20TN%2C%20TX%2C%20UT%2C%20VA%2C%20VT%2C%20WA%2C%20WI%2C%20WV%2C%20WY&api_key=VBJvAbqe0D9w3pyhaHcw4p4MB2dNgSgxMjvCbyEH" -H "accept: application/json"
How can I add this to my javascript to make this work when I just want to put in the 2 character state abbreviation?
"use strict";
const apiKey = "VBJvAbqe0D9w3pyhaHcw4p4MB2dNgSgxMjvCbyEH";
const searchURL = "https://api.nps.gov/api/v1/parks";
function formatQueryParams(params) {
const queryItems = Object.keys(params).map(
key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
);
return queryItems.join("&");
}
function displayResults(responseJson) {
// if there are previous results, remove them
console.log(responseJson);
$("#results-list").empty();
// iterate through the items array
for (let i = 0; i < responseJson.data.length; i++) {
// for each park object in the items
//array, add a list item to the results
//list with the park title, description,
//and thumbnail
$("#results-list").append(
`<li><h3>${responseJson.data[i].fullName}</h3>
<p>${responseJson.data[i].description}</p>
<a href='${responseJson.data[i].url}'>${responseJson.data[i].url}</a>
</li>`
);
}
//display the results section
$("#results").removeClass("hidden");
}
function getNationalParksInfo(query, maxResults = 10) {
const params = {
key: apiKey,
q: query,
limit: maxResults - 1
};
const queryString = formatQueryParams(params);
const url = searchURL + "?" + queryString;
console.log(url);
fetch(url)
.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}`);
});
}
function watchForm() {
$("form").submit(event => {
event.preventDefault();
const searchTerm = $("#js-search-term").val();
const maxResults = $("#js-max-results").val();
getNationalParksInfo(searchTerm, maxResults);
});
}
$(watchForm);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>National Parks by Location</title>
<link rel="stylesheet" href="style.css" />
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"
></script>
</head>
<body>
<div class="container">
<h1>Your National Parks</h1>
<form id="js-form">
<label for="search-term">Search term</label>
<input type="text" name="search-term" id="js-search-term" required />
<label for="max-results">Maximum results to return</label>
<input
type="number"
name="max-results"
id="js-max-results"
value="10"
/>
<input type="submit" value="Go!" />
</form>
<p id="js-error-message" class="error-message"></p>
<section id="results" class="hidden">
<h2>Search results</h2>
<ul id="results-list"></ul>
</section>
</div>
<script src="app.js"></script>
</body>
</html>
The desired outcome is for me to either type the full state name of the state abbreviation and I get the same search results.

Trying to implement socket.io with node.js express and react onto my production server

Having issues integrating socket io + express js onto my Bluehost server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Poll App</title>
<link rel="stylesheet" href="/style.css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container" id="react-container">
<h1>Live Polling</h1>
</div>
<!-- <script src="/socket.io-client/dist/socket.io.js"></script> -->
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="./dist/bundle.js"></script>
<!-- <script src="/socket.io/socket.io.js"></script> -->
</body>
</html>
here's my app.js
var React = require('react');
var Router = require('react-router');
var RouteHandler = Router.RouteHandler;
var Header = require('./parts/Header');
var io = require('socket.io-client');
var APP = React.createClass({
getInitialState(){
return {
status : 'disconnected',
title : '',
member : {},
audience: [],
speaker : '',
questions: [],
currentQuestion: false
}
},
componentWillMount(){
this.socket = io('react-test.derrickmv.com');
this.socket.on('connect', this.connect);
this.socket.on('disconnect', this.disconnect);
this.socket.on('welcome', this.updateState);
this.socket.on('joined', this.joined);
this.socket.on('audience', this.updateAudience);
this.socket.on('start', this.start);
this.socket.on('end', this.updateState);
this.socket.on('ask', this.ask);
},
emit(eventName, payload){
this.socket.emit(eventName, payload);
},
connect(){
var member = (sessionStorage.member) ? JSON.parse(sessionStorage.member): null;
if (member && member.type ==='audience'){
this.emit('join', member);
} else if (member && member.type === 'speaker'){
this.emit('start', {name: member.name, title : sessionStorage.title});
}
this.setState({ status: 'connected'});
},
disconnect(){
this.setState({
status: 'disconnected',
title: 'disconnected',
speaker: ''
});
},
updateState(serverState){
this.setState(serverState);
},
joined(member){
sessionStorage.member = JSON.stringify(member);
this.setState({ member: member});
},
start(presentation){
if( this.state.member.type === 'speaker'){
sessionStorage.title = presentation.title;
}
this.setState(presentation);
},
ask(question){
sessionStorage.answer = '';
this.setState({ currentQuestion: question });
},
updateAudience(newAudience){
this.setState({ audience: newAudience});
},
render(){
return (
<div>
<Header {...this.state} />
<RouteHandler emit={this.emit} {...this.state} />
</div>
);
}
});
module.exports = APP;
After placing everything into my server, I get the following errors in the console log stating a 404 (Not Found) Error.
Here's my app-server.js:
Thanks so much for helping!

Categories

Resources