Nuxt.JS: How to get post parameter data in a vue file - javascript

I am integrating paytm payment gateway in my nuxt js project. Buy I am
unable to get post data with which paytm is redirecting to my callback
url.

Since asyncData gives you access to req and res (see https://nuxtjs.org/guide/async-data/#use-reqres-objects), you can parse the body to get POST parameters. I found this solution out there, so I didn't try it out. In fact, it should be better to use a Middleware to parse this and load the middleware in that page.
<script>
export default {
asyncData ({ req, res }) {
if (process.server) {
const qs = require('querystring')
let body = ''
let temp = ''
let paymentData = ''
while(temp = req.read()) {
body += temp
}
paymentData = qs.parse(body)
return { data: paymentData }
}
},
data () {
return {
paymentData: '',
}
},
mounted () {
console.log(this.paymentData)
}
</script>

Related

nextjs getServerSideProps vs API

I'm trying to understand the main difference between getServerSideProps and just using useSWR inside of the page component. If I run something like this inside getServerSideProps:
export const getServerSideProps = async () => {
try {
const palettes = []
const docRef = query(collection(db, 'palettes'), orderBy('likes', 'desc'), limit(16))
const docData = await getDocs(docRef)
docData.forEach((doc) => {
palettes.push(doc.data())
})
if (!docData) {
return {
props: {
data: { error: 'Failed to load palettes. Please refresh the page.'}
}
}
} else {
return {
props: {
data: { palettes }
}
}
}
} catch (e) {
console.log('error:', e)
}
}
It will run at build time and then on each request by the user when viewing/navigating to the page?
Then what would be the difference from just using useSWR or another API fetcher like:
export default function PaletteSlugs({ slug }) {
const { data, error } = useSWR(`/api/palette/${slug}`, fetcher)
return (
{data}
)
}
Also could this affect how many request/reads will happen on the database?
Simply, using getServerSideProps will get the API data on the Node.js server, while the HTML page will be completely populated by Node.js on the server. If you try to open the page source in the browser you will see all data already exists in the page source, this will be better for SEO.
But with useSWR will get the data on the client-side like normal fetch and the data will be populated on the client-side.

Sveltekit Error: `page` in `load` functions has been replaced by `url` and `params`

I am trying to display my date from GraphCMS in my blog application. I receive this error when I go to my single post link (http://localhost:3000/posts/union-types-and-sortable-relations)
"
page in load functions has been replaced by url and params
Error: page in load functions has been replaced by url and params
"
Here is my code
<script context='module'>
export const load = async ({fetch, page: {params}}) => {
const {slug} = params
const res = await fetch(`/posts/${slug}.json`)
if(res.ok) {
const {post} = await res.json()
return {
props: {post},
}
}
}
</script>
<script>
export let post
</script>
<svelte:head>
<title>Emrah's Blog | Welcome</title>
</svelte:head>
<pre>{JSON.stringify(post, null, 2)}</pre>
Can you please help. Thanks
Try using params instead of page: params, though the latter still works in Sveltekit 278 (which I'm using).
Besides, I'm curious to know what makes you prefer this method to querying GraphCMS for your single post. I do it like this:
import {client} from '$lib/js/graphql-client'
import {projectQuery} from '$lib/js/graphql-queries'
export const load = async ({ params }) => {
const {slug} = params
const variables = {slug}
const {project} = await client.request(projectQuery, variables)
return {
props: {
project
}
}
}
Yes, this has been changed a while ago, now the different parts of what used to be page are passed directly into the load function:
export async function load({ fetch, page }) {
const { params, url } = page
}
export async function load({ fetch, params, url }) {
}
Something else to consider is that now there are page endpoints, if your file is [slug].svelte you can make a file [slug].js and add the following:
export async function get({ params }) {
const { slug } = params;
const post = {}; // add the code to fetch from GraphCMS here
return {
status: 200,
body: {
post
}
}
}
With this you can remove the load function and make your code simpler (especially because you technically already have all this code in your /posts/[slug].json.js file.
<script context='module'>
export async function load({ fetch, params}){
let id = params.users
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
const user = await response.json()
if(response.ok){
return {props:{user}}
}
return {
status: response.status,
error : new Error(" sorry no user found")
}
}
export let user

Trying to send data from client side but req.session doesn't work properly

I'm trying to do post request, and it is very successful when I do it with postman, but I'm trying to send it from my client-side. I want to post the cart, but as a result I'm constantly posting item with quantity of 1 no matter of fact how many times do I post that request. What is the best solution to fix this and post the request on the normal way?
I'm using session, maybe that would cause the problem sending request from frontend?
This is my post request:
app.post("/add-to-cart/:id", async (req, res) => {
try {
const id = req.params.id;
const { data } = await axios.get("http://localhost:4200/products");
const singleProduct = await data.find((product) => product._id === id);
let cart;
if (!req.session.cart) {
req.session.cart = cart = new Cart({});
} else {
cart = new Cart(req.session.cart);
}
req.session.cart = cart;
cart.addProduct(singleProduct);
console.log(req.session.cart)
res.send(cart);
} catch (error) {
console.log(error);
}
});
This is the Cart code:
module.exports = function Cart(oldCart) {
this.productItems = oldCart.productItems || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0.00;
this.addProduct = function(item) {
let storedItem = this.productItems;
if (!storedItem.hasOwnProperty("item")) {
storedItem = this.productItems = {item: item, qty: 1, price: item.price};
this.totalQty = 1;
this.totalPrice = item.price;
} else {
storedItem = {item: item, qty: storedItem.qty, price: storedItem.price};
console.log("STORED ITEM: ", storedItem);
this.productItems = storedItem;
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.item.price;
}
}
}
This is the function which I put on my button with #click.prevent="addToCart()"
addToCart(){
let productId = this.oneProduct.id;
Cart.postCart(productId);
}
I'm sending this from axios service on frontend:
postCart(productId){
return cartService.post(`/add-to-cart/${productId}`);
}
There are no warnings or errors when I try to interact with this on client side. This is the output which I get in my backend (constantly repeating the information of a single product nevertheless this works normally on the client side):
if you are using frontend framework either angular,vue,react or anything that supports routing. you don't need to use res.redirect to change route and get the data.
how about you use res.send(cart) to return the cart data and do the rerouting in the frontend.
async postCart(productId){
cartService.post(`/add-to-cart/${productId}`);
// history.push('/your-next-route')
}
I think there's a problem at this line:
req.session.cart = cart = new Cart({});
The reason this assignment does not work as expected is explained here: Multiple left-hand assignment with JavaScript
you should change it to:
cart = new Cart({});
The rest of logic should work.
like your seesionId is't sent to backend, are you using fetch or axios?
fetch:
fetch('https://example.com', {
credentials: 'include'
})
axios:
{withCredentials: true}
Maybe the server and client are cross-domain?
Set the appropriate value of samesite, see this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

How to speed up getServerSideProps with next js?

When I'm using getServerSideProps with next js and it almost takes 5 or 6 seconds for the page to load . I tried using only one url to fetch and not many but again it takes alot for the page to load .
export const getServerSideProps = async (ctx) => {
let data ;
try {
data = axios.get("url")
} catch(e){
data = "error"
}
return {
data: data,
};
};
I was wondering is there any trick to speed up getServerSideProps data fetching so I could have faster initial page load ?
got this solution while searching for this bug
const isServerReq = req => !req.url.startsWith('/_next');
function Post({ post }) {
// Render post...
}
export async function getServerSideProps({ req }) {
const initData = isServerReq(req) ? await fetch(...) : null;
return {
props: {
initData,
},
}
}
issue: https://github.com/vercel/next.js/issues/13910

Display API JSON response in template - Angular

I want to display data on my website from JSON file from URL.
I work on Angular and I've create a HttpClient in my component. Code below show all document in console, so here is my question.
let resp = this.http.get("https://spreadsheets.google.com/feeds/cells/1w2vpgbwImaQGCbpMqZ3P0NC93tuVved0oOFc9Zr22dU/1/public/full?alt=json");
resp.subscribe((data)=>console.log(data));
Can I show a specify elements from this JSON file?
I want to display data from: feed -> entry -> gs$cell -> $t on my website.
How I should start, what I need?
I have add a picture how the JSON array looks and what elements I want to get and show on my website.
Store API response in a class variable i.e data, assume sample data
data = {
feed: {
entry: [
{ gs$cell: { $t: 'Nazwa' } },
{ gs$cell: { $t: 'pazwa' } },
{ gs$cell: { $t: 'shuzwa' } }
]
}
}
Accessing directly in template
<div *ngFor="let d of this.data.feed.entry">{{d.gs$cell.$t}}</div>
It seems to me that your problem is how to extract the data.
I can't use your HttpClient so I will be using fetch API for demonstration.
async function getData() {
const endpoint =
"https://spreadsheets.google.com/feeds/cells/1w2vpgbwImaQGCbpMqZ3P0NC93tuVved0oOFc9Zr22dU/1/public/full?alt=json";
// const json = await http.get(endpoint);
const response = await fetch(endpoint);
const json = await response.json();
const { feed } = json;
const { entry: feedEntries } = feed;
return feedEntries.map((entry) => {
const { gs$cell } = entry;
const { $t } = gs$cell;
return $t;
});
}
(async () => {
const data = await getData();
console.log(data);
// do whatever you wan't with the data, use it on your template maybe?
})();

Categories

Resources