getServerSideProps access current browser url - reactjs

I am calling getServerSideProps and passing in the req and res parameters like this:
export async function getServerSideProps({ req, res }) {}
I need to get the current browser url path and I can't find it in the request object.
Is there a way to get the current url inside getServerSideProps?

You can use the resolvedUrl field from the context parameter.
export async function getServerSideProps({ req, res, resolvedUrl }) {
console.log(resolvedUrl)
// Remaining code
}
From the getServerSideProps documentation:
resolvedUrl: A normalized version of the request URL that strips the
_next/data prefix for client transitions and includes original query values.
Note that resolvedUrl will not return the domain part of the URL, only the path and query string are returned.

Related

How to do a HTTP head request in next.js

I want to achieve the same done here but in next.js.
Next.js provides methods to fetch data from a server and using them as props. I don't know whether you want to use it before rendering a page (like getServerSideProps) or when, for example, you click a button, but I suppose its the first case.
My personal preference when doing requests, is axios, so I will use it in this example:
export async function getServerSideProps({ req, res }) {
// Here is where we make the request
const result = await axios({
method: 'HEAD', // here is where we declare that we want to use the HEAD method
url: "your server url", // this is the url where we want to send the request
headers: {} // if you want to add custom headers, you can do it here
})
// Here we are logging the result of the request
console.log(result)
}
You can refer to the next.js documentation on data fetching and the axios documentation
Have a great day and I hope you succeed on your projects

Get cookie/localStorage value in nextjs API request

I'm trying to get cookie or localStorage value in my API request. When I'm trying to access localStorage I get error that localStorage is not defined, cookies are undefined, I tried my luck with AsyncLocalStorage, but I'm getting error that window is undefined. There is any way to get saved value in this asynchronous function?
import AsyncLocalStorage from '#createnextapp/async-local-storage'
export default async (req, res) => {
try {
let data = await AsyncLocalStorage.getItem('#key')
console.log(data)
}catch(error){
console.log(error)
}
}
This is expected. When you process the data in your API it is actually running in the server. Localstorage, and cookies however are browser based storage (This is also why window is undefined, servers don't have windows). As a result they are not available to the API to leverage. Instead when you make the API request you need to add the data into a header which can then be parsed on your server.
Setting a header on your request:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
From there you should be able to read the headers through:
(req, res) => {
// look at all these great headers we have
const { headers } = req;
}

send data, url, and method to axios as arguments

I am trying to make custom request with axios and pass the method, url and body as arguments like that
const response = await axios({ url, body, method });
but the body doesnot reach to the backend. what is the right way to send data like that?
The config property you're searching for is called data not body. Rename your variable to data and pass it or don't use the object shorthand operator and rename it to data. Like this:
const response = await axios({ url, data: body, method });
In the axios documentation is a list of all available properties.

When an object is sent along with a get/post request express returns an empty object for req.body

When I send an object as a parameter of my post or get request express doesn't seem to receive it
I have tried get and post requests both on the front end and on the server. All the dependencies are working fine (body-parser, etc.)
front end:
axios.get('http://localhost:4000/videoComments/comment', {pauseTime: 10})
or
axios.get('http://localhost:4000/videoComments/comment', {data:{pauseTime: 10}})
back-end:
videoCommentsRoutes.route('/comment').get(function (req, res) {
console.log(req.body);
req.body is an empty object. req.data, req.params are all undefined
GET request supports only query parameters. axios (as well as any of fetch or XMLHTTPRequest wrappers, such as superagent) should transform your object into query string.
Try using req.query to get the query parameters.
Here is express docs about it.
Back-End should be like
videoCommentsRoutes.route('/comment/:pauseTime').get(function (req, res) {
console.log(req.params.pauseTime);
})
or
videoCommentsRoutes.route('/comment').get(function (req, res) {
console.log(req.query.pauseTime);
})
Front-end Call like
axios.get('http://localhost:4000/videoComments/comment', {params:{pauseTime: 10}})

Accessing data inside my API with axios post request

I'm trying to send an object with my get request so I can use it to retrieve data from the backend like so:
axios.get('/', {
params: {
mainID: usersID.id,
otherID: usersID.otherID
}
});
Now at my API I want to access that params object, how do I do that?
router.get('/', (req, res) => {
//how to access params?
});
You can access the route parameters in Express by req.params
From the documentation:
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
Take a look at the Route Parameters section at: https://expressjs.com/en/guide/routing.html
Hope this helps!

Resources