why am I getting 'GET/ 304 --' in my code? (vue.js, express) - javascript

When I request data on client(vue.js) with axios,
I got a error code in server side, 'GET/ 304 --'
But I don't know why this happened
and how to approach this problem or how to fix that.
If I delete codes about 'axios' on client side,
That error doesn't show up.
Please can someone help me.
the code below:
Client side
created() {
axios
.get("http://localhost:4000/")
.then(
result => (
(this.greeting = result.data.greeting),
(this.greeting2 = result.data.greeting2)
)
);
}
Server side
export const getHome = async (req, res) => {
let user;
if (req.headers.authorization !== undefined) {
try {
user = auth.verify(req.headers.authorization);
user = await models.User.findOne({
where: { id: user.id }
});
} catch (err) {
console.log(err);
}
} else {
user = null;
}
const name = user ? user.name : 'Please LOGIN';
res.json({ greeting: `Welcome to Chat N Chill`, greeting2: name });
};
auth.verify code on server side
verify(token) {
return jwt.verify(token.replace(/^Bearer\s/, ''), SECRET_KEY);
}

Express will automatically set the status code to 304 for requests that are fresh:
https://github.com/expressjs/express/blob/e1b45ebd050b6f06aa38cda5aaf0c21708b0c71e/lib/response.js#L206
The property fresh is defined here:
https://github.com/expressjs/express/blob/e1b45ebd050b6f06aa38cda5aaf0c21708b0c71e/lib/request.js#L467
It is documented here:
https://expressjs.com/en/4x/api.html#req.fresh
It should be nothing to worry about, it just means that the content of the response hasn't changed relative to what the browser already has in its cache.

Related

res.redirect not workig when working with React

I am using react as frontend and made api using express I have the following code I have stored jwt token in the cookies while logging in for the first then when trying to login in again I check if there is already a token in the cookies if there is token in the cookie (currently I am not verifying it I just want it to work) redirect the user to profile page but it doesn't work.
Although an XMLHttpRequest can be seen in the network tab (click for screenshot) but it doesn't work.
PS - I am using Axios in the frontend to make a get request.
loginRouter.get("/", async (req, res) => {
try {
const cookieFound = req.cookies["login-token"];
if (cookieFound) {
res.redirect("profile");
} else {
res.redirect("login");
}
} catch (error) {
console.log(error);
res.status(500).json("Ooops something went wrong!");
}
});
code to make a get request in the frontend
useEffect(() => {
Axios.get("/login");
}, []);
EDIT :-
Backend
loginRouter.get("/", async (req, res) => {
try {
const cookieFound = req.cookies["login-token"];
if (cookieFound) {
res.send("/profile");
}
// res.status(200).json(cookieFound);
} catch (error) {
console.log(error);
res.status(500).json("Ooops something went wrong!");
}
});
Client
useEffect(() => {
const alreadyLoggedIn = async () => {
const url = await Axios.get("/login");
window.location = url.data;
};
alreadyLoggedIn();
}, []);
To what you have entered I think you should change window.location = url.data to window.location = window.location.hostname + url.data;
In your current setup the total url will be set to /profile while you want yourwebsite.com/profile

Shopify REST API Pagination using Node.js and Express

I'm facing an issue, using Product resource on Shopify REST Api : I need to display many products on a Node.js Express app, I've left the default limit at 50 and when I want to fetch the next page of 50 products when I click on a next or previous button (I use the nextPageUrl/prevPageUrl from the response headers) I get a 401 error if the request is made from the client-side because of CORS error
Then I tried to make the request on server-side, I've passed the link from client to server when hitting the next button for example but it still does not work
The documentation is not clear at all about the paginated request and nothing that i've done from the documentation now is correct, it just says "Make a GET request to the link headers" and voila
Anyone have done this before ?
Code below
protectedRouter.get('/inventory', async (req, res) => {
try {
const session = await Shopify.Utils.loadCurrentSession(req, res);
const client = new Shopify.Clients.Rest(session.shop, session.accessToken)
const result = await client.get({
path: 'products',
})
res.render('inventory', {
products: result,
})
} catch (error) {
throw error;
}
});
script(src="/scripts/pagination.js")
div.View
h3.title.my-4 Etat des stocks
div.row
div.col-6
span(id='previousLink') #{products.pageInfo.prevPageUrl ? products.pageInfo.prevPageUrl : '' }
button.btn.btn-outline-dark.ml-4(id="previous_btn")
i(class="bi bi-arrow-left-circle-fill") Précédent
div.col-6
span(id='nextLink') #{products.pageInfo.nextPageUrl ? products.pageInfo.nextPageUrl : '' }
a.btn.btn-outline-dark.float-right.mr-4(id="next_btn") Suivant
i(class="fa-solid fa-circle-arrow-right")
window.addEventListener('DOMContentLoaded', () => {
console.log('dom content loaded')
document.getElementById('next_btn').onclick = function (e) {
console.log('next button clicked')
const nextLink = document.getElementById('nextLink').innerHTML;
fetch(nextLink).then(response => {
console.log(response);
}).catch(error => {
console.log(error)
})
console.log(nextLink)
}
});
You're doing it wrong. If you want to display Shopify products in your own App, you use the StorefrontAPI calls. With a StorefrontAPI token, you get products, and can display them. Trying to use Admin API calls is never going to work properly. Switch to StorefrontAPI and all your problems go away.

How can I resolve this pdf-generator problem?

I'm new at field.
I trying to make pdf generator web application with express.js using html-pdf package.
I have condition on engagement variable
module.exports =
({rs,periode,engagement,siren,num,rue,codePostal,ville,contratRef,commentaire,nomPrenom,fonction,phone,mail}) => {
const today = new Date();
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
window.onload = function test() {
var o = (document.getElementById('choix1'));
var u = (document.getElementById('choix2'));
if (${ engagement } == "oui") {
o.checked = true;
}else if (${ engagement } == "non") {
u.checked = true
}
}
</script>
When client send data to back end the app crashed and error "cannot set headers after they are sent to the client" in my terminal. how can I resolve this problem ?
Server API code:
app.post('/pdf', (req, res) => {
pdf.create(pdfDocument(req.body), {}).toFile('result.pdf', (err) => {
if(err) { res.send(Promise.reject()); }
res.send(Promise.resolve());
});
});
We normally get cannot set headers after they are sent to the client if response is returned twice or if headers are set after response is returned. You can read more about it in following stack overflow post:
Error: Can't set headers after they are sent to the client
If response object is not being updated from any other middleware apart from request handler code shared, there are chances that pdf.create returned error and res.send got called twice -
within if block for error and
res.send statement after if
If you add return before res.send like below, issue should be resolved
app.post('/pdf', (req, res) => {
pdf.create(pdfDocument(req.body), {}).toFile('result.pdf', (err) => {
if(err) {
return res.send(`Error in generating PDF`);
}
return res.send(`PDF created successfully!`);
});
});
Also, I am not sure why you are returning Promise.resolve() / Promise.reject() in response.

Express.js - Cannot Set Headers with exported function

Learning how to do testing with Express with using Mocha, Chai, Chai-HTTP plugin, and MongoDB with Mongoose. I have a test to purposely detect if MongoDB will send back an error from trying to find a document using a faulty _id value (too short).
I noticed that part of my code is repeating around my other Express routes, and want to reuse it for other routes so I exported it from another module, but now I get this:
Uncaught Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Not sure why I am getting this error. If I have the same code, as the exported function, inside the route code it works fine, but exported it just complains.
Here is the code:
test/route/example.test.js Snippit
it('Bad request with a too short ID string (12 characters minimum)', () => {
// /api/v1/example is the endpoint
// /blah is the param
chai.request(app).get('/api/v1/example/blah').end((err, res) => {
// Insert all the nice assert stuff. :)
});
});
route/example.js Snippit
// Packages
const router = require('express').Router();
// Models (Mongoose Schemas)
const Example = require('../models/example.model');
// Helpers
const { foundMongoError } = require('../helpers/routes');
// -----Snipped-----
router.route('/:exampleId').get((req, res) => {
// Retrieve the exampleId parameter.
const exampleId = req.params.exampleId;
Example.findById(exampleId, (mongoError, mongoResponse) => {
foundMongoError(mongoError, res); // Having an issue
// If I have the same code that makes up foundMongoError inside here, no issues,
// but it will no longer be DRY.
// Check if any responses from MongoDB
if(mongoResponse) {
res.status(200).json(mongoResponse);
} else {
return res.status(404).json({
errorCode: 404,
errorCodeMessage: 'Not Found',
errorMessage: `Unable to find example with id: ${exampleId}.`
});
}
});
});
helpers/routes.js
const foundMongoError = (mongoError, res) => {
if(mongoError) {
return res.status(400).json({
errorCode: 400,
errorCodeMessage: 'Bad Request',
errorMessage: mongoError.message
});
}
};
module.exports = {
foundMongoError
};
That just means you send and response res twice back. The first time you send it back at here:
if(mongoError) {
return res.status(400).json({
errorCode: 400,
errorCodeMessage: 'Bad Request',
errorMessage: mongoError.message
});
}
You sended an response back but the function still continue its work, that means the function moves on till here then:
if(mongoResponse) {
res.status(200).json(mongoResponse);
} else {
return res.status(404).json({
errorCode: 404,
errorCodeMessage: 'Not Found',
errorMessage: `Unable to find example with id: ${exampleId}.`
});
}
Here happens the second response, and here you get the error.
I would rewrite the code like this:
Instead of returning the response, you return an true that means there is an error, otherwise false :
const foundMongoError = (mongoError, res) => {
if(mongoError) {
res.status(400).json({
errorCode: 400,
errorCodeMessage: 'Bad Request',
errorMessage: mongoError.message
});
return true;
}
return false;
};
module.exports = {
foundMongoError
};
Then you can write it like this:
if(foundMongoError(mongoError, res)) return;
The return will stop the function to execute the rest of the code

How to display 404 page if a back-end GET request to an API fails because user doesn't exists? Separated front-end and back-end

I have an application that uses JavaScript with Vue.js for the front-end and PHP with Laravel for the back-end.
Right now, when I make a GET request from my front-end to my back-end on URL /getSummoner/{summonerName}, I make another GET request from my back-end to a third party API in order to get the details for a user with a certain summoner name like this:
public function getSummoner($summonerName){
$summoner = Summoner::where('summoner_name', $summonerName)->first();
if ($summoner === null) {
$apiKey = env("RIOT_API_KEY");
$region = env("EUW");
$getSummonerInfo = file_get_contents($region . "/lol/summoner/v4/summoners/by-name/" . $summonerName . "?api_key=" . $apiKey);
$summonerInfo = json_decode($getSummonerInfo);
$summoner = new Summoner();
$summoner->summoner_name = $summonerName;
$summoner->summoner_info = json_encode($summonerInfo);
$summoner->save();
} else {
$summonerInfo = json_decode($summoner->summoner_info);
}
return response()->json([
'summonerInfo' => $summonerInfo,
], 201);
}
And then I return a JSON response to my front-end with the summoner info. This all works fine and dandy as long as a user with that summoner name exists. If he doesn't exists, the GET request fails so the rest of my function fails and in return I get an error on my front-end.
So I am wondering what am I supposed to do to get a 404 page on the front-end if my back-end GET request doesn't go through? Both on the front and back-end. I assume I need to return some sort of response from the back-end and then based on that response do something on the front-end?
Here's my front-end:
<template>
<div>{{ summonerInfo }}</div>
</template>
<script>
import axios from 'axios'
import router from '../router'
export default {
data(){
return {
summoner: this.$route.params.summonerName,
summonerInfo: '',
}
},
methods: {
user(action){
let trimmedSummoner = this.summoner.replace(/\s+/g, '');
axios.get('/' + action + 'Summoner/' + trimmedSummoner)
.then((response) => {
this.summonerInfo = response.data.summonerInfo
})
.catch(function (error) {
console.log(error);
})
}
},
watch:{
$route (to, from){
this.summoner = this.$route.params.summonerName
this.user('get')
}
},
mounted(){
this.user('get')
}
}
</script>
One poor mans way of doing this would be to wrap your request in a try / catch. This way, when you request fails, you have the opportunity to catch it and redirect. Downside to this method is that it doesn't give you any info on what the status code is (4xx vs 5xx, etc...).
However, a proper solution would be to use Http Interceptors to handle this.
How can you use axios interceptors?
Here is another example using try / catch approach:
https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253
They've also got quite a few examples on this within their GitHub Docs:
https://github.com/axios/axios
Interceptor Example:
axios.interceptors.response.use((response) => {
if(response.status === 401) {
alert("You are not authorized");
}
return response;
}, (error) => {
if (error.response && error.response.data) {
return Promise.reject(error.response.data);
}
return Promise.reject(error.message);
});

Categories

Resources