JavaScript express, node and CSVtoJSON - javascript

I'm currently developing a 'Dupe Finder' web app for a co-worker. This is my first time using the 'csvtojson' package.
I'm reading from the file just fine on the server, but when I send a response back to the client (ideally containing a json object) I'm getting this very odd console log and I'm not sure if its correct:
To get this response, I have a button on the home page, when clicked, the client makes an http request on the home directory of the server, called '/getnums'. The request reads from the CSV then should be returning and obj with its contents. It is sort of doing that, in the screenshot, if I click the tick next to promiseValue, it'll give me an array. But i'm not sure why its returning a Promise..anyway..
api.js:
var CSVDATA = () => {
fetch('/getnums')
.then(res => {
console.log(res.json())
})
}
export default {
CSVDATA,
}
'/getnums' goes to my router, which is simly router.get('/', mainController.getNums)
in the controller is where the reading begins:
const csv = require('csvtojson')
module.exports = {
getNums: (req, res, next) => {
const csvFilePath = `${__dirname}/../../client/readFrom/main.csv`
csv().fromFile(csvFilePath)
.then(jsonObj => {
return res.status(200).json(jsonObj)
})
.catch(e => {
req.error = e
next()
})
},
}
anyone have an idea what might be going on here?

That is simply how .json() works.
It returns promise so you need to handle it asynchronously
var CSVDATA = () => {
fetch('/getnums')
.then(res => res.json())
.then(json => console.log(json));
}
export default {
CSVDATA,
}
MDN link

Related

Nested promises receiving 301 error code and cors for second fetch

I am attempting to create an API where you type in a player's name and you get the player position, team and then stats. The only thing is that while it uses the same public API, Ball Don't Lie, it requires two different fetches. So I am attempting to get the player id from the first promise and then feed it into the second. I get the first info and the id but when I attempt the second fetch I get this: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://balldontlie.io/api/v1/stats?season[]=2020&player_ids[]=237. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Status code: 301.
Here is my code:
//The user will enter a NBA player, click on the type of stat, team, and receive their stats. Default will be all stats?
document.querySelector('button').addEventListener('click', apiRequest)
function apiRequest() {
var player = document.querySelector('input').value;
var season = document.querySelector('input[type="number"]').value;
var id;
fetch(`https://www.balldontlie.io/api/v1/players/?search=${player}`)
.then(res => res.json()) //parse response as JSON
.then(data => {
object = data;
id = object.data[0].id;
document.querySelector('h2').innerText = `${data.data[0].first_name} ${data.data[0].last_name}`
document.querySelector('.team').innerText = data.data[0].team['full_name']
document.querySelector('.position').innerText = data.data[0].position
//nested fetches to send player id from one promise to another promise to get player stats
})
.then (async data => {
await new Promise(data => {
return fetch (`https://balldontlie.io/api/v1/stats?season[]=${season}&player_ids[]=${id}`)
.then(response => response.json())
.then(data => {
array[index] = {...e, ...data};
console.log(data)
})
})
})
.catch(err => {
console.log(`error ${err}`)
})
}
I am using Node.js and Express so I am using CORS package. Below is my server.js.
const express = require('express');
const app = express();
const PORT = 8000;
const cors = require('cors');
app.use(cors());
//Body Parsing
app.use( express.json() );
app.use(express.urlencoded({
extended: true}));
app.use(express.static("public"));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
})
app.listen(PORT, () => {
console.log(`The server is running on ${PORT}`);
})
First off, your code is a bit confused for the second fetch() operation and in fact the promise created here in await new Promise(data => {...}). never resolves because you never call the first argument to the executor function (which you have inappropriately named data when it should be resolve).
Second, you don't have proper error handling on some of your promises so you may not be clearly seeing what errors are happening here.
So, first I'd suggest cleaning up the code and error handling and then rerun it to report exactly what you get:
//The user will enter a NBA player, click on the type of stat, team, and receive their stats. Default will be all stats?
document.querySelector('button').addEventListener('click', apiRequest)
function apiRequest() {
const player = document.querySelector('input').value;
const season = document.querySelector('input[type="number"]').value;
console.log("about to run first fetch()");
fetch(`https://www.balldontlie.io/api/v1/players/?search=${player}`)
.then(res => res.json()) //parse response as JSON
.then(data => {
console.log("got first fetch() result");
const object = data;
const id = object.data[0].id;
document.querySelector('h2').innerText = `${data.data[0].first_name} ${data.data[0].last_name}`;
document.querySelector('.team').innerText = data.data[0].team['full_name'];
document.querySelector('.position').innerText = data.data[0].position;
//nested fetches to send player id from one promise to another promise to get player stats
console.log("about to run second fetch()");
return fetch(`https://balldontlie.io/api/v1/stats?season[]=${season}&player_ids[]=${id}`)
.then(response => response.json())
.then(data => {
console.log("got second fetch() result");
// not sure what array is here?
// It isn't declared anywhere - shouldn't be doing this
array[index] = { ...e, ...data };
console.log(data)
});
}).catch(err => {
console.log(`error ${err}`)
});
}
And, I've added a little more logging about which fetch() operation is running so if you see an error displayed, you can see which fetch() operation caused it.

400 bad request with ReactJs

I'm trying to make a post request to the server,but it returns 400 error.
:
this is react function
const handleSubmit = () => {
const bookInstanceObject = {
imprint: imprint,
};
axios
.post('http://localhost:3001/catalog/bookinstance/create', bookInstanceObject)
.then(res => {
console.log(res.data);
})
.catch(error => {
console.log(error);
});
};
and this is the server side:
router.post('/bookinstance/create', (request, response, next) => {
const body = request.body;
const bookInstance = new BookInstance({
imprint: body.title,
});
bookInstance
.save()
.then(savedBook => {
response.json(savedBook.toJSON());
})
.catch(error => next(error));
});
any idea ?
What I think is happening
The front end's handleSubmit function is POSTing to /catalog/bookinstance/create, while the server is expecting it to come to /bookinstance/create.
Simple typo, easy to miss when your stressing over it not working.
How to fix?
Change the URLs to match.
Either:
change the front-end's POST url to /bookinstance/create,
or:
change the server's expected route to router.post('/catalog/bookinstance/create',
Why is it a GET in the error log?
I don't know but I suspect that this error is about a GET request somewhere else in your code.
Please let us know in the comments if the error goes away with this fix. (Assuming my fix works)

Formdata not being sent through to NodeJS backend

I have a function that should send FormData as an axios.post call to my api. It gets activated with a press of a button
const sendCard = (card) => {
debugger;
let data = new FormData();
data.append("itemID", itemID);
data.append("comment", comment);
data.append("dateStart", dates[0]);
data.append("dateEnd", dates[1]);
data.append("qtyWant", qtyWant);
requestBooking(data);
};
and here is the axios part:
export const requestBooking = async (data) => {
return await api
.post(`/booking/request`, data)
.then((data) => {
return "DONE!";
})
.catch((err) => {
console.log(err.response.data);
});
};
the api is an import from a config.js file, and everything there works with all the other aspects of my website.
I have another FormData object being posted into the api, and that one works properly, even though there is no differences at all...
Here is the accepting function on the back end
app.post(
"/api/booking/request",
request
);
exports.request = (req, res) => {
res.status(200).send("Reached");
};
where req.body is just an empty object ({})
This all seems like it should work. And I don't know what am I missing

Why Axios response doesn't console log result?

I'm working on an backend API but at some point I need to get user data from another API. I am trying to use Axios to make http request in order to do that. The request return the result in the browser as expected but the problem is that I can't display console log in the terminal. It doesn't show anything even though I asked the program to do so. Is there a problem probably with my code?
Here is my code :
const axios = require('axios');
const AxiosLogger = require('axios-logger');
const instance = axios.create();
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
console.log(response.data);
return response.data
})
.catch(error => {
console.log(error);
});
});
};
I would suggest trying response.send to forward the axios response to your client like so:
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
// Send the axios response to the client...
res.send(response.data)
})
.catch(error => {
console.log(error);
});
});
};

How to get myshopify custom page content from server

I have created the my custom page called "pages.api.main-menu.liquid"
When I access page from preview mode it shows the the content.
The case is I want to take the content of this page from Next Server. So I sent a request directly to this page.
export default (req, res) => {
const {
SHOPIFY_STORE_URL,
SHOPIFY_ADMIN_API_KEY,
SHOPIFY_ADMIN_API_PASSWORD
} = process.env
serverCoreAPI
.get(
`https://${SHOPIFY_ADMIN_API_KEY}:${SHOPIFY_ADMIN_API_PASSWORD}#${SHOPIFY_STORE_URL}/pages/main-menu-api`
)
.then((response) => {
console.log(response)
res.status(200).send(response.data || { data: null })
})
.catch((e) => {
console.log(e)
})
}
I am taking as a response the error code 400.
Anyone can help with this?

Categories

Resources