I'm just start using graphql with apollo client, I have graphql server setup and is running localhost:4000, and here is my client
index.js
const client = new ApolloClient({
uri: "http://localhost:4000/graphql",
cache: new InMemoryCache()
});
blog.js
const GET_BLOG = gql`
{
post(id:"5ab2b46d941953bf614e2617") {
title
body
user {
name
email
}
}
}
<Query query={GET_BLOG}>...</Query>
I got everything working, my question is there way I can change the graphql endpoint url name, so instead of graphql, can I have something like /graphql/post, /graphql/user, I have the scheme in graphql server, but if I do two call, it will just return two /graphql in network tab
SERVER.applyMiddleware({
app: APP,
path: '/newEndPoint'
});
Set path attribute within applyMiddleWare Options object. Now visit
localhost:<port>/newEndPoint for the grap
As far as I know, graphql only use one endpoint url name, in your case is http://localhost:4000/graphql , if you want separated endpoint, it is just like REST routing
Related
I have a test API under: pages\api\accounts\login.js. And I am learning the new app folder, which is still an experimental feature in Next.js (as of today).
Is it possible to move my login script into the app folder? I tried moving/renaming to app\api\accounts\login\pages.js, but when I do this:
async function handler(req, res) {
console.log(res);
}
export default handler;
I use the URL: http://localhost:3000/api/accounts/login. I get:
Server Error
Error: Cannot find module for page: /api/accounts/login
I also tried moving it to: app/api/accounts/login/page.js. But I get the same error.
As you can read on the API Routes page of the new documentation of Next.js, API routes are currently as before, meaning they should be in the pages/api folder:
API routes should still be defined in the pages/api/* directory and not moved to the app directory.
We are considering what API routes would look like in the app directory and will update this page in the future.
Some use cases where an API route was used to keep access tokens secure when calling an external API from the client can now be done directly in Server Components.
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a route.
For example, the following API route pages/api/user.ts returns a json response with a status code of 200:
// pages/api/user.ts
import { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
I am trying to access params in my Next.js API routes. I am just wondering why in order to access a certain dynamic route id I must use req.query when normally in express I would access the id via params. Is req.query the correct way of accessing the id?
I have the following api folder structure.
/pages
/api
/posts
-index.js
-[postId].js
In my [postId] file I have the following
function handler(req, res) {
// shows undefined
console.log(req.params);
const postId = req.params.postId;
and my api call is as follows:
fetch(`/api/posts/${id}`)
Referring to nextJs docs, all examples uses req.query to get the id or other parameters:
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
So there's nothing wrong with this approach.
Nextjs doesn't explicit says why they use query instead of params, but in the section about dynamic routes you can get some clues:
the route /post/abc?foo=bar will have the following query object:
{ "foo": "bar", "pid": "abc" }
Probably they use query as a way to join both params and query in one object or it's just more convenient to use that way, so as there's no reference about it you don't have to care that much, just use the query and be happy.
I want to call an API in asyncData()
async asyncData({ $axios, params, store }) {
let itemUUID = params.item;
let item = await $axios.get("/item/" + itemUUID);
return {item};
}
Problem: Axios is still making the request on http://localhost:3000
if I do a console.log($axios.defaults.baseURL) the correct baseURL of my API is printed.
This also works if I use my store action & make the call by using this.$axios
I am using #nuxtjs/axios 5.13.1 with Nuxt 2.15.6 in SSR mode and configured it with the correct baseURL in the nuxt.config.js
Interestingly, if I edit my page content and a hot module reload is triggered, the correct URL is used. Maybe the question should be if Axios is triggered in the right time, on the server?
Edit: I checked the request that was made on HMR and this was triggered in the client.js.
If I call my store inside the created() hook the request gets executed successfully.
My nuxt.config.js:
publicRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL,
}
},
I'm not sure what is the NODE_TLS_REJECT_UNAUTHORIZED=0 thing doing but your frontend configuration (Nuxt) is working well so far.
Sorry if I cannot help on the Express part.
Maybe try to setup HTTPS locally on Nuxt: How to run NUXT (npm run dev) with HTTPS in localhost?
TLDR; This was not related at all - I forgot to set the auth token for my backend. At the time of axios init it's not present. $axios object doesn't have auth - backend fails.
On page load the nuxt function nuxtServerInit() is used to get the auth token out of the acces_token cookie.
I am using a plugin to initialize Axios - with the token from the store.
But of couse the token is not present at the time axios is initialized as nuxtServerInit is called after plugin init.
In my axios.js plugin I changed:
export default function({ app, error: nuxtError, store }) {
const token = const token = store.state.user.token;
app.$axios.setToken(token, "Bearer");
}
to;
export default function({ app, error: nuxtError, store }) {
const token = app.$cookies.get("access_token");
app.$axios.setToken(token, "Bearer");
}
Now the token is present & used for every request happening server-side.
In my React app, hosted on Azure as a Static Web App, I use the MSAL library for authentication. In order to create a new Msal.UserAgentApplication, I need to pass a configuration object - which in particular contains the redirectUri. Something like:
const msalConfig = {
auth: {
clientId: "75d84e7a-40bx-f0a2-91b9-0c82d4c556aa",
authority: "https://login.microsoftonline.com/common",
redirectUri: "www.example.org/start",
},
...
I'm wondering: how can I use a relative redirect url, not an absolute one?
The concrete problem I'm trying to solve is the following one: when I launch and test the app locally, then I want to redirect to localhost:3000/start instead of www.example.org/start. So far I haven't found any better method than switching the config file before each run/deploy, but it's annoying and of course can be easily forgotten...
You can make it dynamic like this:
const msalConfig = {
auth: {
redirectUri: window.location.origin + '/start'
}
}
This takes the current origin and adds /start to the end.
This way it works locally and in the deployed environment(s).
I want to disable caching or restrict the cache to 24 hours. My ApolloClient runs exclusively on the Server side.
My environment:
apollo-boost 0.4.3
graphql 14.1.1
apollo-link-batch-http - 1.2.12
Right now, that's how I configure my ApolloClient.
new ApolloClient({
ssrMode: true,
cache: new InMemoryCache(),
link: WithApollo.BatchLink(),
credentials: 'same-origin',
});
The closest thing I saw in docs is FetchOptions ... But it doesn't specify what options i can actually pass to achieve my need for disabling or restricting the cache.
This is not possible with Apollo Boost. You need to migrate to migrate to using Apollo Client. This will allow you to provide a defaultOptions option to your ApolloClient constructor as shown in the docs:
const defaultOptions = {
watchQuery: {
fetchPolicy: 'no-cache',
},
query: {
fetchPolicy: 'no-cache',
},
}
The fetchPolicy option can actually be set on each individual query call or Query component -- by providing a defaultOptions object, you avoid having to specify no-cache as the fetch policy on each individual Query component you use. That also means if you're bent on keeping Boost, you could just do this on each of your components. However, the above is how to effectively "turn off" caching for the whole client.
Maybe someone want to know how to disable caching of apollo-boost ApolloClient exactly, so let's talk about it.
#Daniel said is truth, we cannot disable the caching when we do new ApolloClient of apollo-boost directly, but we can set fetchPolicy when we send out the request. The code as below:
// create client first
import ApolloClient from "apollo-boost";
const client = new ApolloClient({ uri: GRAPHQL_URL })
// Set the fetchPolicy when we send request
import { gql } from 'apollo-boost';
client.query({
query: gql`
query someInfo($id: ID!) {
info(id: $id) {
id
name
}
}`,
variables:{id: '123'},
fetchPolicy: 'no-cache'
})
The valid value for fetchPolicy you can find from there.