soy nuevo aprendiendo node.js y estoy tratando de insertar datos a una tabla de postgres pero recibo el error ” Cannot set headers after they are sent to the client” enter image description here
Alguien podria guiarme ?
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
soy nuevo aprendiendo node.js y estoy tratando de insertar datos a una tabla de postgres pero recibo el error ” Cannot set headers after they are sent to the client” enter image description here
Alguien podria guiarme ?
I am trying to search for a name from JSON data in search bar , but can’t get it as a text. (I am getting a successful response in a log). I am not sure if looping through array to search for a file_name is a right way to search a data
Here is my code below
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 => {
for (var i = 0; i < nbaData.length; i++) {
if (nbaData[i].first_name === playerSearch) {
messageOne.textContent === nbaData[i].first_name
} else {
messageOne.textContent = 'not found'
}
}
})
})
})
Requesting a data which is exported
const nbaPlayerData = (callback) => {
axios.request(options).then((response) =>{
var data = response.data.data
return callback({data: data})
}).catch(function (error) {
console.error(error);
});
}
the main app where I get these data from json
`
const express = require('express')
const hbs = require('hbs')
const axios = require('axios')
const path = require('path')
const networkManager = require('./utils/nba-network.js')
const app = express()
const viewsPath = path.join(__dirname, '../templates')
const publicPath = path.join(__dirname, '../public')
app.set('view engine', 'hbs')
app.set('views',viewsPath) //
app.use(express.static(publicPath))
app.get('/nba', (req,res) => {
networkManager.nbaPlayerData((data)=>{
res.send({
playerName: data.data
})
console.log(data)
})
})
app.get('', (req,res) => {
res.render('index', {
playerName: res.data
})
})
app.listen(4000, () => {
console.log('Server is runnin on a 4000 port')
})
`
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 player name">
<button>Search</button>
</form>
<p id="player-1"></p>
</div>
<script src ="/js/fetch-app.js"></script>
</body>
</html>
`
I know that in google maps you can compare ride services like freenow and bolt. Does google provide any API that returns this data?
Thanks!
I didn’t find anything, but i find it strange that google doesn’t have an API to get this data.
I use Selenium 3.14 with remote WebDriver for testing a website in Chrome. Test cases are in Java. JUnit4. In one of the tests there is a drag and drop simulated / performed by JavaScriptExecutor. Normally, once a file is dropped on a designated WebElement, there is a popup where user can enter details regarding the file. When I start the test case from my Eclipse or from my own Jenkins, there are no issues, the required popup is displayed and can be worked with.
Same code, same node, same website, copies of the same file, but test started from the different Jenkins and the popup doesn’t appear and there are no errors thrown.
The drag and drop method is from this selenium post with only difference that I reworked the following due to exception saying proxy element cannot be casted
WebDriver driver = ((RemoteWebElement)target).getWrappedDriver();
Anyway, I am totally lost regarding why I get different behaviour. Both Jenkins are of the same version and use same jdk, if it even matters. The file to be dropped is stored on file system of each respective Jenkins.
Please advise me what should I check or try out in Jenkins config or my code to find out the reason.
In attempt to investigate I brought my functional Jenkins to the same version as the “bad” one; ensured I use the same jdk on both machines.
I’m trying to get the ip of the clients who connects to my node server via a middleware, but for some reason, I only get the local ip. The project is hosted on a web-hotel, but all I get is 127.0.0.1. No matter if I connect to it, or my friend who lives in another country.
Code:
async function getUserIp(req, res, next) {
console.log(req.socket.remoteAddress);
Next();
}
I’m not sure if I’m missing something in my code, or if it is the environment itself on the web-hotel I use, hence why I only get local ip.
I would use HeatMap chart from ApexChart. https://apexcharts.com/docs/installation/
They are using generateData
method to demonstrate the data structure ApexChart
requires. But what kind of data generateData
produce? 🙂
class ApexChart extends React.Component {
constructor(props) {
super(props);
this.state = {
series: [{
name: 'Jan',
data: generateData(20, {
min: -30,
max: 55
})
},
I imported a third-party player library as Player
.
I see there are two predefined functions in Player
, addModule
& getModules
.
Now I need to add some ‘non-existance’ properties like: EventType
import Player from "bitmovin-player";
import BtmPlayer from "./BtmPlayer";
import chai from 'chai';
import sinon from 'sinon';
describe("BtmPlayer", function () {
var sandbox;
var player;
beforeEach(function () {
sandbox = sinon.createSandbox();
/* create stubs for existent property */
sandbox.stub(Player, "addModule").returns(true);
sandbox.stub(Player, "getModules").returns(['module1', 'module2']);
/* create a stub for non-existent property */
sandbox.stub(Player, "PlayerEvent").returns({ // Issue: throwing error
Error: "error",
Ready: 'ready',
Play: 'play',
Paused: 'paused'
});
});
afterEach(function () {
sandbox.restore();
});
it("BitmovinPlayer Instance", function () {
player = new BtmPlayer();
chai.expect(player).to.be.an.instanceOf(BtmPlayer);
});
)};
It’s not working.
It’s throwing errors like: TypeError: Cannot stub non-existent property
.
Have you any idea, —
We have a project setup with Laravel and Mix, Vue (2.7) and Vue-i18n which was working up to now. We recently had to ugprade to Mix 6 and Webpack 5 in order to install TailwindCSS and the Vue-i18n loader is no longer working.
Here’s my config:
webpack.mix.js
:
const mix = require('laravel-mix');
mix.extend( 'i18n', new class {
webpackRules() {
return [{
resourceQuery: /blockType=i18n/,
type: 'javascript/auto',
loader: '@intlify/vue-i18n-loader',
}];
}
}());
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css/app.css')
.options({
postCss: [
require("tailwindcss"),
]
})
.i18n();
package.json
:
{
"private": true,
"scripts": {
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"production": "mix --production"
},
"dependencies": {
"autoprefixer": "^10.4.13",
"axios": "^0.19.0",
"bootstrap": "^4.4.1",
"bootstrap-vue": "^2.5.0",
"browserslist": "^4.8.7",
"caniuse-lite": "^1.0.30001030",
"cross-env": "^5.2.1",
"jquery": "^3.4.1",
"laravel-echo": "^1.6.1",
"laravel-mix": "^6.0.49",
"lodash": "^4.17.15",
"nprogress": "^0.2.0",
"popper.js": "^1.16.1",
"postcss": "^8.4.19",
"pusher-js": "^4.4.0",
"resolve-url-loader": "^5.0.0",
"sass": "^1.32.13",
"sass-loader": "^11.1.0",
"tailwindcss": "^3.2.4",
"vue": "^2.7.14",
"vue-bootstrap-typeahead": "^0.2.6",
"vue-i18n": "^8.15.3",
"vue-progressbar": "^0.7.5",
"vue-router": "^3.1.5",
"vue-template-compiler": "^2.6.11",
"vuejs-datepicker": "^1.6.2",
"vuex": "^3.1.2"
},
"devDependencies": {
"webpack-cli": "^5.0.1"
},
"main": "tailwind.config.js"
}
The error I’m getting now is:
Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
in every file where I’m referencing vue-i18n
This is cart page of a ecommerce site.
Here I want to get the value of each indivisual counter value and multiply that with their respective price and show it into final checkout value. Here, i had hardcoded $160 but I want to make that dynamic. How can I do that or what would be best approach to achieve that.
My cart page
import React, { useState } from 'react'
import { RiDeleteBin6Line } from "react-icons/ri"
import Counter from '../../Components/Counter/Counter'
const Products = ({ cartdetails }) => {
const [value, setValue] = useState()
return (
<div className=' grid grid-cols-12 gap-4'>
{cartdetails.length === 0 ?
<div>No items in cart</div>
:
<div className=' col-span-8'>
{
cartdetails.map((data, index) => {
return (
<div className=' bg-gray-100 px-4 my-4 py-4'>
<div className=' flex justify-between'>
<img className=' w-24 h-24' src={data.productdetails.image} alt="" />
<div className=''>
<div className=' font-semibold text-lg'>
{data.productdetails.name}
</div>
<div className=' text-gray-400 text-sm'>
Color : {data.cartItems.color}
</div>
</div>
<div>
<div className='font-semibold text-lg'>${data.productdetails.price} USD</div>
<div className='text-gray-400 text-sm'>Price</div>
</div>
<div>
<div className=' font-semibold text-lg'>{data.productdetails.stock}</div>
<div className='text-gray-400 text-sm'>In Stock</div>
</div>
<button className=' h-fit text-gray-400'>
<RiDeleteBin6Line />
</button>
</div>
<Counter count={data.cartItems.quantity} {...data.productdetails} />
</div>
)
})
}
</div>
}
<div className=' col-span-4 my-4 '>
<div className=' px-4 py-8 flex flex-col gap-8 bg-gray-100'>
<div className=' flex justify-between'>
<div className=' font-bold'>Total</div>
<div className=' font-semibold'>$160USD</div>
</div>
<div className=' flex justify-end '>
<button className=' btn w-36 font-bold'>Checkout</button>
</div>
</div>
</div>
</div>
)
}
export default Products
Counter Component
import React, { useState } from 'react'
import { HiOutlineMinus } from "react-icons/hi"
import { GoPlus } from "react-icons/go"
import { incrementItem, decrementItem } from '../../redux/cart/changeCartNumber'
import { useSelector, useDispatch } from 'react-redux'
const Counter = ({ count, stock, _id }) => {
const [value, setValue] = useState(count)
return (
<div className='flex font-bold text-xl justify-end'>
<div className=' flex gap-4 bg-white p-2 w-40 justify-between '>
{/* <button className={`${state.value === 1 && "text-gray-400"}`} disabled={state.value === 1} onClick={() => dispatch(decrementItem({ _id, count }))}><HiOutlineMinus /></button> */}
<button onClick={() => setValue(value - 1)} disabled={value === 1} className={`${value === 1 && "text-gray-400"}`} ><HiOutlineMinus /></button>
<div>
{value}
</div>
<button onClick={() => setValue(value + 1)} disabled={value === stock} className={`${value === stock && "text-gray-400"}`}><GoPlus /></button>
</div>
</div>
)
}
export default Counter
It says MODULE_NOT_FOUND, I don’t know what to do, I have installed discord.js also
E:Selio-New-Bot>node .
node:internal/modules/cjs/loader:417
throw err;
^
Error: Cannot find module 'E:Selio-New-Botindex.js'. Please verify that the package.json has a valid "main" entry
←[90m at tryPackage (node:internal/modules/cjs/loader:409:19)←[39m
←[90m at Module._findPath (node:internal/modules/cjs/loader:651:18)←[39m
←[90m at resolveMainPath (node:internal/modules/run_main:19:25)←[39m
←[90m at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:24)←[39m
←[90m at node:internal/main/run_main_module:23:47←[39m {
code: ←[32m'MODULE_NOT_FOUND'←[39m,
path: ←[32m'E:\Selio-New-Bot\package.json'←[39m,
requestPath: ←[32m'E:\Selio-New-Bot'←[39m
}
Node.js v19.2.0
T
I tried to create a command and I was expecting it to save and work.
I’m using azure pipeline for running automation, i have seperate two stages is one for automation functional and one for check UI.
In stage functional, after each run, a new account will be created and insert to file account to run for the following test cases and i’m using read file to read the account file to get the newest account and everything is good in stage functional.
But have problem that in stage UI, when i’m using readfile , it can’t not get newest account that is created in stage functional, it only can get the old account that in repo. And also that the stage UI can be run after stage functional is finished
`
async readFile(path){
return new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (err, jsonString) => {
if (err) {
console.log("File read failed:", err);
return;
}
resolve(JSON.parse(jsonString))
});
})
}
`
can find someone that have experience with that to resolve the problem
I want an advice for creating a Custom Landing Page in my project.
My actual need is to allow clients to customized selected HTML Template.
We can allow them to change all data exist in template. We can allow more than this if any one have any one is thiking it is easy.
We can do this by rich text box but it only allows inline css,
but it will be appriciated if anyone can has solution for using external CSS because we need to allow to do Theme change too.
All types of suggestion will be aprriciated.
Thanks in Advance.
I tried
https://stripo.email/en/demo/?template=1395565&project=516180&guid=34a0ffa3-9cea-40fc-a82d-6937f6e6d616
and rich text box too
I’m building my first Vue app. I have some experience with React, and I’m trying to make a simple movies list in Vue.
There are two bugs in my app – both related to the button toggling:
Am I missing something?
<template>
<div v-for="(name, index) in movies" :key="index" class="movieContainer">
<div class="center">
{{ name.name }}
<button
@click="name.hideImg = !name.hideImg && toggle(name.id)"
class="watchBtn"
>
<p v-if="!name.hideImg">►</p>
<p v-else>▼</p>
</button>
</div>
<div v-show="name.id == open">
<video controls="controls" autoplay name="media">
<source
:src="require(`@/assets/movie${index + 1}.mp4`)"
alt="video"
type="video/mp4"
width="500px"
/>
</video>
</div>
</div>
</template>
<script>
export default {
name: "App",
methods: {
toggle(id) {
this.open = this.open === id ? null : id;
},
},
data() {
return {
movies: [
{
name: "Pokemon",
duration: "1hr 12min",
hideImg: false,
open: null,
id: 1,
},
{
name: "Digimon",
duration: "2hr 37min",
hideImg: false,
open: null,
id: 2,
},
{
name: "Transformers",
duration: "1hr 51min",
hideImg: false,
open: null,
id: 3,
},
{
name: "Kiepscy",
duration: "1hr 51min",
hideImg: false,
open: null,
id: 4,
},
],
};
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin: 60px auto 0;
}
.watchBtn {
background-color: red;
border-radius: 10px;
margin-left: 10px;
height: 20px;
display: flex;
align-items: center;
}
.watchBtn:hover {
background-color: rgb(255, 191, 107);
cursor: pointer;
}
.movieContainer {
margin: 5px auto;
display: flex;
flex-direction: column;
}
.center {
margin: 0 auto;
display: flex;
}
.movieContainer video {
width: 500px;
}
</style>
I am have a map function which iterates through a list of stock tickers, on each iteration I want to perform a GET request using the stock ticker’s. I am trying to perform the GET request within the map function like below:
import React from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
import { useEffect, useState } from 'react';
import { response } from 'express';
const App = () => {
const [messages, setMessages] = useState([] as any[]);
const [px, setPx] = useState([] as any[]);
React.useEffect(() => {
axios
.get(
'https://api.stocktwits.com/api/2/streams/trending.json',
{}
)
.then((response) => {
setMessages(response.data.messages);
})
.catch((ex) => {
let error = axios.isCancel(ex)
? 'Request Cancelled'
: ex.code === 'ECONNABORTED'
? 'A timeout has occurred'
: ex.response.status === 404
? 'Resource Not Found'
: 'An unexpected error has occurred';
// setError(error);
// setLoading(false);
});
}, []);
console.log(messages);
return (
<div className="App">
<table className="messages_table">
<tr>
<th>Tweeted at</th>
<th>Tweet</th>
<th>User</th>
<th>Tweet sentiment</th>
<th>Symbols mentioned</th>
</tr>
{messages.map((message) => (
<tr>
<td>{message.created_at}</td>
<td>{message.body}</td>
<td>
{' '}
{message.user.name} ({message.user.username})<br></br>{' '}
Followers: {message.user.followers}
</td>
<td>{message.entities?.sentiment?.basic}</td>
{message.symbols.map(
(symbol: {
symbol:
| string
| number
| boolean
| React.ReactElement<
any,
string | React.JSXElementConstructor<any>
>
| React.ReactFragment
| React.ReactPortal
| null
| undefined;
title: string;
}) => {
let symb = symbol.symbol;
const sendGetRequest = async () => {
try {
const resp = await axios.get(
`https://ql.stocktwits.com/batch?symbols=${symb}`
);
setPx(resp.data.symb.Volume);
} catch (err) {
// Handle Error Here
}
};
React.useEffect(() => sendGetRequest(), []);
return (
<td>
{symbol.symbol} - ({symbol.title})<br></br>
</td>
);
}
)}
</tr>
))}
</table>
</div>
);
};
export default App;
However, I know using a HOOK within the callback isn’t permitted but without it just constantly performs API request. Can someone suggest how I can get this working please
I am using tradingview widget with javascript. When the page loads, BTCUSDT is the USDT equivalent. In the upper right corner, we can change the currency of a different country from the price conversion. Is it possible to select different country automatically with widget settings on code??
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
<script type="text/javascript">
new TradingView.widget({
"width": "100%",
"height": "100%",
"symbol": "<?php echo $pairname; ?>USDT",
"interval": "D",
"timezone": "Etc/UTC",
"theme": "dark",
"style": "1",
"locale": "tr",
"currencies": "KWD",
"toolbar_bg": "#f1f3f6",
"enable_publishing": false,
"allow_symbol_change": true,
"container_id": "tradingview_b75ce"
});
</script>