I am building a nuxt application and I am facing an issue with Proxy and Async data.
This is my nuxt.config (simplified)
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true
},
proxy: {
'/api': {
target: 'http://www.example.com',
pathRewrite: {
'^/api': '/'
}
}
}
This is my asyncData code fragment (simplified):
async asyncData ({ store }) {
await store.dispatch('fetchData')
}
Store action fetchData code (simplified):
async fetchData({ commit }) {
const response = await myService.fetchData()
commit('setData', response.data)
}
And at last, myService function (simplified):
fetchData () {
return axios.get('/api/path-to-my-resource')
}
What is expected:
To have the service triggering a call to the proxied endpoint, on both cases: visiting the page through a link or refreshing the page
What is happening:
When I hit refresh on the page, instead of firing a call to the http://www.example.com/path-to-my-resource, I see that it tries to do it at /api/path/to-my-resource and of course it fails. From what I understand, when I refresh the page, the proxy is not working inside the asyncData hook.
I am pretty sure that there is something that I attempt wrongly, but I cannot find it. Can someone point me towards the right direction?
Try something like:
proxy: {
'/api/': { target: 'http://www.example.com', pathRewrite: {'^/api/': ''} }
// ^^^^^ ^^^^^^ ^^
// Note the ending slashes.
// And the rewrite rule.
}
That's how the docs are written:
http (ky) module: https://http.nuxtjs.org/api/#proxy
Axios module: https://axios.nuxtjs.org/options#proxy
Related
I’m trying to get apollo-server-lambda or apollo-server-express to work with an executable schema for v3.36.
Here are the packages we use:
apollo-server-express#3.36 or apollo-server-lambda#3+
graphql-constraint-directive#3.0.0
#graphql-tools/schema#7.1.3
I ran multiple regression test to make it work, and it does not seem to hit GraphQL.
Here’s my Apollo server config:
const apolloServer = new ApolloServer({
schema: initializeSchema(),
plugins: [
ApolloServerPluginLandingPageGraphQLPlayground(),
{
didEncounterErrors(errors) {
logger.info(`didEncounterErrors:`)
logger.info(errors)
},
async requestDidStart(requestContext) {
logger.info(`Request started! ${requestContext}`);
return {
async parsingDidStart(requestContext) {
logger.info(`Parsing started! ${requestContext}`);
},
async validationDidStart(requestContext) {
logger.info(`Validation started! ${requestContext}`);
}
}
},
}],
context: async ({ event, context, express }) => {
logger.info(`Loading event... ${JSON.stringify(event)}`)
const newContext = {
headers: event.headers,
functionName: context.functionName,
event,
context,
expressRequest: express.req,
user: {} ?? null,
}
logger.info(`context ${JSON.stringify(newContext)}`)
return newContext
},
dataSources: () => {
logger.info('!initializing datasource')
initializeDbConnection()
return {}
},
...(['staging', 'production', 'demo'].includes(process.env.stage as string)
? { introspection: false, playground: false }
: {}),
})
I was able to log the executable schema inside initializeSchema, but it does not seem to hit the GraphQL Typedef and Resolver after upgrading. It just goes straight to context. So, I'm kinda stumped how to make HTTP request hit the Typedef and Resolvers using makeExecutableSchema()
I just need some advise or a list of table that could help me which version works best with the given apollo-server-<server_version>.
I am using next js as a front-end and laravel as a back-end. and i want to call back-end (laravel) api from getServerSideProps() method. as shown below
export async function getServerSideProps(context) {
const response = await Axios.request({
url: 'http://localhost:8000/api/event',
method: 'get',
headers: {
Cookie: context.req.headers.cookie,
},
})
const events = response.events
console.log(response)
return {
props: { events },
}
}
so i have also set the cookie but i am getting response with message unauthenticated like below
I just wanted to say a huge THANK YOU to Riaz Kahn for his answer. After a lot of banging my face against a wall this was the answer. I'm going to post a working example of my getServerSideProps function for anyone arriving here in the future. The getUser({[configObject]}) function is just returning a promise from an axios.get('my-user/route', config) call. This is working properly in a Next 13 app using standard pages functionality (not using experimental app directory).
export const getServerSideProps = async (context: any) => {
const {req, res} = context;
try {
const {data: user} = await getUser({
headers: {...req.headers}
});
return {
props: {
fallback: {user}
}
}
} catch (e) {
res.writeHead(302, {Location: '/login'});
res.end();
}
}
I am trying to get nuxt-socket-io working on my NuxtJS application, but my emit functions do not seem to trigger the actions in my vuex store.
nuxt.config.js has the following code:
modules: [
'#nuxtjs/axios',
'nuxt-socket-io'
],
io: {
sockets: [
{
name: 'main',
url: process.env.WS_URL || 'http://localhost:3000',
default: true,
vuex: {
mutations: [],
actions: [ "subscribeToMirror" ],
emitBacks: []
},
},
]
},
That subscribeToMirror action is present in my vuex store (in index.js):
export const actions = {
async subscribeToMirror() {
console.log('emit worked');
try {
new TopicMessageQuery()
.setTopicId(state.topicId)
.setStartTime(0) // TODO: last 3 days
.subscribe(HederaClient, res => {
console.log("Got response from mirror...");
return res;
});
} catch (error) {
console.error(error);
}
}
};
And that action should be triggered by the emit in my index.vue script:
mounted() {
this.socket = this.$nuxtSocket({
name: 'main',
reconnection: false
})
},
methods: {
...mapMutations([
'setEnv',
'initHashgraphClient',
'setTopicId',
'createNewTopicId'
]),
...mapActions([
'createAndSetTopicId'
]),
subscribeToMirror() {
console.log("method worked");
return new Promise((res) => {
this.socket.emit('subscribeToMirror', {}, (resp) => {
console.log(resp)
resolve()
})
})
}
}
While I can see the 'method worked' console output from index.vue's subscribeToMirror method, I have never seen the 'emit worked' message. I have played around with this for hours, copying the instructions from this guide but have had no success.
Can anyone spot what I'm doing wrong?
UPDATE: I tried copying the code from this example and was unable to get a response from that heroku page. So it appears that I am completely unable to emit (even though $nuxtSocket appears to be functional and says it's connected). I am able to confirm that the socket itself is up and running, as I was able to get responses from it using the ticks from that example. I'm putting the repo for this project up here for viewing.
UPDATE2: I made a much simpler project here which is also not functioning correctly but should be easier to examine.
It turns out that while nuxt-socket-io functions as a wrapper for socket.io stuff you still need to actually create the server. This is a good template for how to do this
I'm using multiple external APIs with Nuxt.js and axios, bet I have problems with SSR. When requests are coming from client-side this config is working and proxy is changing url, bet when requests are coming from server (on app page reload) proxy not hitting and axios using baseURL, which is one for all requests.
nuxt.config.js
axios: {
proxy: true
},
proxy: {
'/api/': {
target: process.env.FIRST_API_URL,
pathRewrite: {
'^/api/': ''
}
},
'/api2/': {
target: process.env.SECOND_API_URL,
pathRewrite: {
'^/api2/': ''
}
}
},
Api call in one of Vuex store actions as example:
export const actions: ActionTree<CoreState, RootState> = {
async fetchItems ({ commit }) {
await this.$axios.$get('/api2/items').then((response) => {
commit('SET_ITEMS', response.data)
})
}
}
Action is dispatching from component asyncData method:
async asyncData ({ store }) {
await store.dispatch('items/fetchItems')
}
How to make this work both from client-side and server-side ?
I'm trying to use the webpack-dev-server proxy configuration to send api requests to an external domain and I can't seem to get it working.
Here's my config:
var path = require('path')
module.exports = {
entry: './client/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/assets'),
publicPath: 'assets'
},
devServer: {
contentBase: 'public',
proxy:{
'/api/v1*': {
target: 'http://laravelandwebpack.demo/',
secure: false
}
}
}
}
So, anytime my app makes a request with the uri /api/v1... it should send that request to http://laravelandwebpack.demo.
In my Vue app, I'm using the vue-resource to make the requests and I'm defaulting all requests with the needed uri prefix:
var Vue = require('vue')
Vue.use(require('vue-resource'))
new Vue({
el: 'body',
http: {
root: '/api/v1', // prefix all requests with this
headers:{
test: 'testheader'
}
},
ready: function (){
this.$http({
url: 'tasks',
method: 'GET'
}).then(function (response){
console.log(response);
}, function (response){
console.error(response);
})
}
})
The URL's are being constructed correctly, but they're still pointing to localhost:8080 which is the webpack-dev-server:
I read and re-read the docs for webpack-dev-server and I can't figure out where I have it set up wrong. Any ideas?
#Linus Borg is right.
The URL's are being constructed correctly, but they're still pointing to localhost:8080 which is the webpack-dev-server:
This doesn't matter.
In my case, I want to get http://m.kugou.com/?json=true. And I am using #Vue/cli ^3.0.0-beta.15, maybe you need to modify your code according to situation.
So, here is what I did:
App.vue
axios.get('/proxy_api/?json=true').then(data => {
console.log('data', data)
})
vue.config.js
module.exports = {
devServer: {
proxy: {
// proxy all requests whose path starting with /proxy_api to http://m.kugou.com/proxy_api then remove '/proxy_api' string
'/proxy_api': {
target: 'http://m.kugou.com',
pathRewrite: {
'^/proxy_api': '/'
}
}
}
//or just change the origin to http://m.kugou.com
// proxy: 'http://m.kugou.com'
}
}
I use /proxy_api/?json=true then update it to http://m.kugou.com/?json=true by target and pathRewrite.
'/proxy_api' is used to distinguish if the url should be proxied.
Why would I use /proxy_api? Easy to distinguish.
I got the data from http://m.kugou.com/?json=true while the url in the dev-tool is http://localhost:8080/proxy_api/?json=true.
See? that doesn't matter.
I found a workaround solution for that issue. In my case I need to proxy requests to my backend for any /api/* path, so I'm bypassing any requests which does not starts with api.
Sample:
proxy: {
'*': {
target: 'http://localhost:8081',
secure: false,
rewrite: function(req) {
console.log('rewriting');
req.url = req.url.replace(/^\/api/, '');
},
bypass: function(req, res, proxyOptions) {
if (req.url.indexOf('api') !== 0) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}else{
return false;
}
}
}
}