简体   繁体   中英

Next.js - How to get the reaction in getServerSideProps using fetch get query on client

I have a getServerSideProps call on the directory page.

pages/catalog/index.js

export async function getServerSideProps(ctx) {
  const response = await fetch(
    `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.query.page}` : 'page=1'}`,
  )
  const data = await response.json()

  return {
    props: {
      data: data?.data,
    },
  }
}

Is it possible to make a get query with parameters on the client to the catalog page so that getServerSideProps responds to this query and gives a new response each time?

Example of a request on a client: fetch('http://localhost:3000/catalog?page=5')

It is necessary that the getServerSideProps responds to the get request from the client and the url on the client's side is unchanged and equals http://localhost: 3000/catalog

I assume you are asking whether you can pass the entire query string to your getServerSideProps.

You can create a function like this

 serialize = function(obj) { var str = []; for (var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } const props = { page: 1, category: 'abc' } console.log(serialize(props))

and then in your getServerSideProps

export async function getServerSideProps({ query }) {

  query.page = query.page ? query.page : 1 //you can modify it too before serializing 

  const response = await fetch(
    `http://someDomen.com/api/ipro/?${serialize(query)}`,
  )

  const data = await response.json()

  return {
    props: {
      data: data?.data,
    },
  }
}

client side: http://localhost/catalog?page=123&catalog=abc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM