Unable to catch and log the error from axios request
I'm validating user input and result in express and am returning 422 if the input is invalid and a 400 if result is empty. The problem is that I can't log the response object when an error occurs.
Nodejs:
if (q === '' || q.length < 3 || q.length > 150) {
console.log('invalid query');
return res.sendStatus(422).send('Search not found');
} else {
try {
// Fetch redis data
const data = await GET_ASYNC('data');
// stuff here
// Result Validation
if (!Array.isArray(data) || !data.length) {
res.status(400).send('Search not found');
} else {
// do stuff
res.status(200).send(data);
}
} catch (err) {
console.error(err);
res.sendStatus(500); // Server error
}
Now my react code:
const searchDb = useCallback(async() => {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
try {
axios.get(`/api/bestProduct?q=${searchValue}`,
{ cancelToken: source.token })
.then(res => {
console.log(res) // nothing shows up
const data = res.data;
setData(data)
});
} catch (err) {
if (axios.isCancel(err)) {
console.log(err.response); // nothing shows up
} else {
console.log('hello??') // nothing
return setError(`There's been a problem on our end.`)
}
}
}, [])
I've looked at other solution and tried to log the res and res.status but nothing shows up. This is what my console looks like during the error:
See also questions close to this topic
-
Make Query With having, count and join in Sequelize
I have two tables in MySQL, joined with a Many to Many relationship. They are as follows:
Equipments:
Field Type Id PK, Integer name Varchar description Varchar createdAt datetime Instructions:
Field Type id FK, integer name Varchar And the table that joins them as a pivot:
EquipmentInstructions:
Field Type equipmentId FK, integer instructionId FK, integer The query I'm trying to do is this, but getting all the fields, not just the name and description.
SELECT P.equipmentId, E.name, E.description FROM EquipmentInstructions P JOIN Equipments E ON P.equipmentId=E.id WHERE P.instructionId IN (1,2,3) GROUP BY P.equipmentId HAVING COUNT(*)=3;
This query returns:
equipmentId, name, description '8', 'ESPATULA', 'Espátula de cocina' '7', 'PARRILLA', 'Para asar la carne' '4', 'CUCHARÓN', 'Cuchara grande'
I am trying to pass said query to Sequelize, so far I have achieved this:
Equipment.findAndCountAll({ include: [ { model: Instruction, as: "instructions", through: { where: { instructionId: { [Op.in]: [1,2,3], }, }, }, attributes: { include: ["id"], }, }, ], group: ["id"], having: Sequelize.where(Sequelize.fn("COUNT", "*"), "=", recipeIds.length), }) .then((result) => { console.log(result); res.json(result); })
The result is correct, however, I only get the id of the equipment:
{ count: [ { id: 4, count: 3 }, { id: 7, count: 3 }, { id: 8, count: 3 } ], rows: [] }
I need to show the complete information of the equipment and additionally count how many records exist in total (by pagination issues).
-
How to ssr Svelte and pass data from express in node js
I am trying svelte and I might use it for my future website, but there is on thing that has stopped me from suing many js frameworks/compilers. It is server side rendering (one reason is I use server-less so it would be easier then prerendering). Is there a way to use express to server-side-render svelte on every request and also pass data from my node js app too so I don't have to make a bunch of other request? For example the App.svelte might be:
<script> export let data let count = 0 </script> <main> <button on:click={count++}>Increase Count BY 1</button> <h1>{data}<h1> </main>
and main.js:
import App from './App.svelte'; const app = new App({ target: document.body, props: { } }); export default app;
I want to get the data value from the server and use it in the svelte code and also sever-side-render it. Is there a way I can do this?
-
how to send long complex array with socket.io?
I have complex an array containing lots of base64 data. and I send this array to server with socket.io. If I send an array containing one or two base64 data. the function is working successfully. but if I send an array containing lots of base64 data. function does not react.
my purpose
- client will prepare templates.
- When the client clicks the save button, it sends this template to the server with socket.io.
- templates sent to the server will be saved to hdd with nodejs.
my array template
const MyArray = [ { div_id:div.id, div_innerhtml:div.innerHTML, //<img src=base64... div_backgroundimage : div.backgroundimage //base64... } ]
client-side code
const MyArray=[],SaveBtn = document.queryselector("#save_div"); const SendArray = (ARRAY)=>{ socket.emit("div_data",ARRAY); } SaveBtn.onclick = ()=>{ SendArray(MyArray); }
server-side code
socket.on("div_data",(data)=>{ console.log(data) // function does not react. let JSON_DATA = JSON.stringify(data) console.log(JSON_DATA) // function does not react. });
Is this socket.io error? What should I do or how should I research this issue?
UPDATE
network tab in devtools
for two base64 image : (function work successfully)
for four base64 image : (function does not react)
-
Updating React state in nested setTimeout callbacks
Can someone please tell me what's wrong with this and why the state of the 'video variable' remains false? So, even after the h2 element has rendered and is visible (i.e. the state of the video variable has been updated to true), when I click and call the hideVideo function, the video state remains false? Many thanks.
export default function App() { const [message, showMessage] = useState(false); const [video, setVideo] = useState(false); let modalTimeout, videoTimeout; useEffect(() => { window.addEventListener("click", hideVideo); setupTimeouts(); return () => { clearTimeout(modalTimeout); clearTimeout(videoTimeout); }; }, []); const setupTimeouts = () => { modalTimeout = setTimeout(() => { showMessage(true); videoTimeout = setTimeout(() => { showMessage(false); setVideo(true); }, 4000); }, 2000); }; const hideVideo = () => { console.log(video); showMessage(false); if (video === true) { setVideo(false); } }; return ( <div className="App"> {message && <h1>Message</h1>} {video && <h2>Video</h2>} </div> ); }
-
React-dnd multiple elements
I can make react-dnd drag easily having a single element to drag over however I have array of 4 fields I'd like to make draggable. In my example code down below it creates four boxes from mapping the array and each box has a className of 'element'. Which should make them all draggable however they won't move.
Here is my drag code:
const ELEMENT = 'element'; const [{ isDragging }, drag, dragPreview] = useDrag(() => ({ type: ELEMENT, collect: (monitor) => ({ isDragging: monitor.isDragging() }) }))
Here is my draggable element:
{FieldDetail.map((e,i) => <div key={i} ref={dragPreview} style={{ opacity: isDragging ? 0.5 : 1}}> <div className='element' ref={drag}></div> </div> )}
Any ideas? Do I need to do something more within the type or className?
-
One connection - multiple channels
I have 2 watchers, each one creates a socket connection. How to make one connection?
There is a solution to move the connection to the socket into a variable and pass it to Watchers? There is a comment in the code where the socket is connected.
Channels in watchers
export function* watchOnSocketBinanceRT() { while (true) { const { socketToken } = yield take(types.BINANCE_SOCKET_OPEN); const socket = yield call(socketConnectionBinance, socketToken); // Creates a new connection const channel = yield call(socketChannelBinanceRT, socket); if (socket.onopen) { yield put({ type: types.BINANCE_SOCKET_CONNECTED }); } yield fork(socketSendBinance, socket); yield fork(socketCloseBinance, socket); const { cancel } = yield race({ task: call(socketOnmessageBinance, channel), cancel: take(types.BINANCE_SOCKET_CLOSED), }); if (cancel) { buffersRT.flush(); channel.close(); } } } export function* watchOnSocketBinance() { while (true) { const { socketToken } = yield take(types.BINANCE_SOCKET_OPEN); const socket = yield call(socketConnectionBinance, socketToken); // Creates a new connection const channel = yield call(socketChannelBinance, socket); if (socket.onopen) { yield put({ type: types.BINANCE_SOCKET_CONNECTED }); } yield fork(socketSendBinance, socket); yield fork(socketCloseBinance, socket); const { cancel } = yield race({ task: call(socketOnmessageBinance, channel), cancel: take(types.BINANCE_SOCKET_CLOSED), }); if (cancel) { channel.close(); } } }
Socket connection
const socketConnectionBinance = socketToken => { return new Promise((resolve, reject) => { let socket; if (socketToken) { socket = new WebSocket(`${wsUrlBinance()}/${socketToken}`); } else { socket = new WebSocket(`${wsUrlBinance()}`); } socket.onopen = function () { resolve(socket); console.log('Binance connection opened'); }; socket.onerror = function (event) { reject(event); console.log('Binance socket error: ', event); }; socket.onclose = function (event) { if (event.wasClean) { console.log('Binance connection closed'); } }; }); };
Thanks for the help!
-
Parse Multipart Request Body in Node.JS from Flutter Client
I am trying to send along 3 image files to my express server running on Google Cloud Functions.
I am able to get the request to go through, but it is showing up as a buffer on the server.
I am setting fields on the request that I need to grab on the server but am not sure how to parse the
req.body
properly to pull this information off.Future<dynamic> uploadPost(Map<String, dynamic> postData, String placeName, String placeAddress) async { var request = http.MultipartRequest( "POST", Uri.parse('http://localhost:5001/findabite-1ac1a/us-central1/api' + '/posts/add')); request.fields['placeAddress'] = (placeAddress); request.fields['placeName'] = (placeName); request.headers['Content-Type'] = 'application/json'; await Future.forEach(postData.keys, (data) async { final String key = data as String; if (key.startsWith('filePath')) { request.files.add( await http.MultipartFile.fromPath(key, postData[key]), ); } else { request.fields[key] = (postData[key]); } }); request.send(); }
Am I missing something in my client implementation?
This is my express config:
const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const { routes } = require("./src/routes"); const errorHandler = require("./src/middlewares/error_handler"); var app = express(); app.use( bodyParser.urlencoded({ extended: true, }) ); app.use(bodyParser.json()); app.use(cors({ origin: true })); app.disable("x-powered-by"); app.use(routes); app.use(errorHandler); module.exports = { app };
And this is the output of the console when I try to print
req.body
:<Buffer 2d 2d 64 61 72 74 2d 68 74 74 70 2d 62 6f 75 6e 64 61 72 79 2d 34 68 59 48 5f 65 32 77 31 50 65 48 50 57 5f 31 31 4a 51 48 42 47 5a 39 46 4a 31 34 6b ... 309 more bytes>
-
Accordion Collapsible Does not work only in Heroku (CSP Issue)
Iam facing a very strange issue. I implemented some nested collapsible and also simple collapsible that work excellent at localhost.But in Heroku still i cannot understand why collapsibles do not work. Any help is welcomed, without working collapsible my web app will appear chaotic :(
Pug Layout
doctype html html(lang='en') head title= title meta(charset='utf-8') meta(name='viewport', content='width=device-width, initial-scale=1') script(src="https://code.jquery.com/jquery-3.5.1.slim.min.js", integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj", crossorigin="anonymous") link(rel="stylesheet", href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css", integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z", crossorigin="anonymous") script(src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js", integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV", crossorigin="anonymous") link(rel='stylesheet', href='/stylesheets/style.css') body div(class='container-fluid') div(class='row') div(class='col-sm-2') block sidebar ul(class='sidebar-nav') li a(href='/catalog') Home li a(href='/catalog/resources') All Resources li a(href='/catalog/bookings') My Bookings div(class='col-sm-10') block content
Collapsible PUG
extends layout block content -var i=0; -var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] #accordion.panel-group each doc in object flex-container(style='background-color:#c7e7fa; justify-content:space-around; position:relative;flex-direction:row;margin-left:20px;margin-right:auto; margin-top:20px; width:45%; ') .three(style='text-align:center;margin-left:auto; margin-right:auto; flex: 0 0 40%;') h4='' + doc._id.year + ' ' + months[doc._id.month - 1] -i++; #accordion.panel-group .panel-heading h4.panel-title a.accordion-toggle(data-toggle='collapse', href='#collapses' + i) h6 See Total Cost .panel-collapse.collapse.in(id="collapses" + i) .three(style='width:100%; margin-left:auto; margin-right:auto; flex: 0 0 25%;') h5= 'Total Montly Cost: ' + doc.total_cost_month.toFixed(2) .panel-heading h4.panel-title a.accordion-toggle(data-toggle='collapse', href='#collapse'+i) hr h6 See All Booking details .panel-collapse.collapse.in(id="collapse"+i) each booking in doc.bookings_month flex-container(style='background-color:#a6f1a6; width:100%;') three.flex-container | #[strong Start:] #{moment(booking.date_started).format('DD/MM/YYYY HH:mm')} three.flex-container | #[strong Finish:] #{moment(booking.date_finished).format('DD/MM/YYYY HH:mm')} three.flex-container | #[strong Cost:] #{booking.total_cost.toFixed(2)} li else h1 No booking history found h3= 'Start booking now' + " " a(href='/catalog/resources') | here:
-
Express router app.all('*', (req, res, next)) does not get executed on ec2 instance for HTTP requests. Getting request timed out error
I am running a MEAN stack application. It works fine on my localhost. However, when MEAN stack is deployed on AWS ubuntu server HTTP requests are not getting forwarded to the back-end.
The app.js file looks like:
var app = express(); app.all('*', (req, res, next) => { if (req.secure) { return next(); } else { res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url); } });
On my localhost every HTTP request is entering into if(req.secure) loop and respective routers defined in app.js are getting invoked.
However, when i deploy my MEAN stack application on EC2, the control does not enter into the if condition at all.
I have used NGINX reverse proxy to forward the back-end requests are below:
server { charset utf-8; listen 80 default_server; server_name _; location / { root /opt/front-end; try_files $uri /index.html; } location /* { proxy_pass http://localhost:/3000; } }
-
why am I getting "setState is not a function"?
There is a hook in my parent component called
state
, and when the user has submitted his username then it will fetch data and set the state of theParent
component to the fetched object. But javascript sees thesetState
prop as a function I guess, and that's the problem in theChild
component.export const Parent = () => { const [state, setState] = useState("") return ( <div> <Child setState={setState}/> </div> ) }
//
export const Child = ({ setState }) => { const [input, setInput] = useState("") const [username, setUsername] = useState("") useEffect(() => { axios.get("foo.com/" + username) .then(data => setState(data)) .catch(e => console.log(e)) }, [username]) return ( <div> <input type="text" onChange={(e) => setInput(e.target.value)}/> <input type="button" value="" onClick={() => setUsername(input)}/> </div> ) }
-
POST request using axios with set HTTP headers
I have blocked bt CORS policy and I am trying to solve this issue for a while. I have not a lot of knowledge of APIs, so I am really stuck and confused. So I have a basic request to show my response object in the console:
componentDidMount = async () => { const response = await axios.post("http://example.com"); console.log(response); }
But unfortunately, I am being blocked and it says Response to preflight request doesn't pass access control check.
Therefore, I checked the request in curl like this:
curl -d "key=ABCDEFGHIJKLMA" -H "Content-Type: application/x-www-form-urlencoded" -X POST 'http://example.com'
and it works. So I tried to put the header on my code like this but I am not sure if I am doing right.
componentDidMount = async () => { const header = {'Content-Type': 'application/x-www-form-urlencoded'}; const response = await axios.post("http://example.com", {header}); console.log(response); }
If you can help me about this I would be really glad. Thanks!!!
-
Request a graphql query with axios
I'm trying to make a request with a graphql query using axios but failed. this is my query
query { workspace(workspaceName: "stackoverflow") { name company { name } } }
and my code block
axios({ url: "https://testurl.com/graphql", method: 'post', query: ` query($workspaceName: String!) { workspace(workspaceName: $workspaceName) { name company { name } } } `, variables: { workspaceName: CookieHelper.workspaceName, }, forceResolve: resolve, }) .then(res => { resolve(res); }) .catch(err => { reject(err); });
I set it like this because workspaceName value will work parametrically.