Apollo client reaching the wrong httpEndpoint URL when using external config file - javascript

I'm building a nuxt2 website getting all data from a headless Wordpress using wp-graphql and apollo.
As I need possibleTypes data, I've externalized the clientConfigs to another files, here's the info:
nuxt.config.js
...
apollo: {
includeNodeModules: true,
clientConfigs: {
default: '#/apollo/client-configs/default.js',
},
},
...
apollo/client-configs/default.js
import {
InMemoryCache,
IntrospectionFragmentMatcher,
} from 'apollo-cache-inmemory'
import introspectionQueryResultData from './schema.json'
const fragmentMatcher = new IntrospectionFragmentMatcher({
introspectionQueryResultData,
})
export default (context) => {
return {
httpEndpoint: process.env.API_URL,
cache: new InMemoryCache({ fragmentMatcher }),
}
}
When doing that , the SSR is working great, but as soon as I click on a NuxtLink to reach another page, the website crashes with a "Network error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON" error. Looking to the nextwork access, I can see that it's trying to reach the wrong client endpoint:
When I switch back my clientConfigs without the external modules, using:
nuxt.config.js
...
apollo: {
includeNodeModules: true,
clientConfigs: {
default: {
httpEndpoint: process.env.API_URL,
},
},
},
...
The server and client side rendering are both okay now. The network panels of the chrome dev tools can give me the confirmation the good url is reached:
Do someone of you knows why the correct endpoint cannot be reached when using external modules? I'm using "#nuxtjs/apollo": "^4.0.0-rc.19" and "nuxt": "^2.15.8"

Related

Can not get Nuxt.js configuration for Axios to work

I am using Nuxt.js first time now. However I struggle with using the axios module of it somewhat. I like the fact that I can configure the baseUrl in the nuxt.config.js file. I expect. So this is what I did:
// nuxt.config.js
...
axios: {
baseUrl: 'http://localhost:3001',
publicRuntimeConfig: {
axios: {
browserBaseURL: "http://localhost:3004"
}
},
privateRuntimeConfig: {
axios: {
baseURL: "http://localhost:3005"
}
},
},
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next',
'#nuxtjs/proxy'
],
...
Here comes my vue components method I declared to use the Nuxt.js axios module (using this.$axios.$get insteand of this.$axios.get). However I am not sure if there is a difference using this.$axios and just $axios. the latter is called a "plugin" according to the documentation. I did not manage to get axios working with only calling $axios - it can't be resolved so I stick with this.$axios.
Anyway here is method code containing the axios get call. As you can see I am omitting the base url https://localhost since I expect it to be prepended through the nuxt.config.js configuration.
updateTeams: function () {
this.$axios.$get('/api/teams')
.then(({data}) => {
this.teams = data
}).catch((error) => {
console.error(error)
})
}
The result is disappointing. The call is still done with http://localhost:3000 instead of one of the others I configured in the nuxt.config.js file. I rechecked the documentation twice but could not find any hint what I am doing wrong.
Request URL: http://localhost:3000/api/teams

Electron + Vue API requests fall to app://

I've built a Vue app and added Electron to it. I used Vue CLI Plugin Electron Builder
It's ok in development mode, all API requests fall on address which is written in my vue.config.js:
proxy: {
'^/api': {
target: 'http://my-api:3000',
changeOrigin: true
},
},
For example, Axios POST request /api/open_session/ falls to http://my-api/api/open_session as needed.
When I build the project it creates an app:// protocol to open the index.html file.
But it also makes all url paths beginning with app:// including API requests.
My background.js:
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
}
else {
createProtocol('app');
// Load the index.html when not in development
win.loadURL('app://./index.html');
}
I want these paths to be directed to my API, while open all my files as usual (via app protocol)
Well, it's been a longer time and I coped with that on my own. However, here's an answer I came across some forums for those who are struggling with the same issue:
Firstly, I modified my vue.config.js:
proxy: {
'^/api': {
target: 'http://127.0.0.1:3000',
changeOrigin: true
},
},
Then, I made some changes in main.js - added a session variable:
const sesh = session.defaultSession.webRequest.onBeforeSendHeaders({
urls: ['*://*/*']
}, (details, callback) => {
// eslint-disable-next-line prefer-destructuring
details.requestHeaders.Host = details.url.split('://')[1].split('/')[0]
callback({
requestHeaders: details.requestHeaders
})
})
that defines app's behavior when requests get called. Also, I've added a session value to webPreferences:
const win = new BrowserWindow({
width: 1500,
height: 700,
title: "Title",
webPreferences: {
session: sesh,
nodeIntegration: true,
webSecurity: false
}
})
And, finally, load my index.html via app protocol
createProtocol('app');
win.loadURL('app://./index.html');
In result, all my requests got redirected to my server.
Forgive me for not knowing the source, if the author of the code is reading this, you can surely mark yourself in comments :)

(Gatsby-Strapi) Error: Request failed with status code 404

I want to follow the instruction :https://strapi.io/blog/building-a-static-website-using-gatsby-and-strapi#allowaccess
But encounter Error: Request failed with status code 404
Node.js version:
v10.13.0
npm version:
6.14.6
Strapi version:
3.1.0-alpha.5
Operating system:
mac
Which example is causing problem?
strapi.io/blog/building-a-static-website-using-gatsby-and-strapi#allowaccess
What is the current behavior?
Graphql Query doesn't work.
the steps to reproduce the problem:
$ gatsby develop
success open and validate gatsby-configs
success load plugins - 2.011s
success onPreInit - 0.004s
success initialize cache - 0.018s
success copy gatsby files - 0.102s
success onPreBootstrap - 0.017s
success createSchemaCustomization -
info Starting to fetch data from Strapi
info Starting to fetch data from Strapi
info Starting to fetch data from Strapi
ERROR #11321 PLUGIN
"gatsby-source-strapi" threw an error while running the sourceNodes lifecycle:
Request failed with status code 404
Error: Request failed with status code 404
createError.js:16 createError
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/core/createError.js:16 :15
settle.js:18 settle
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/core/settle.js:18:12
http.js:202 IncomingMessage.handleSt reamEnd
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/adapters/http.js:202:1 1
task_queues.js:84 processTicksAndRej ections
internal/process/task_queues.js:84:2 1
What is the expected behavior?
What is the expected behavior?
Doesn't work when I try to get from gatsby
http://localhost:8000/___graphql
There is no method allStrapiblogs on http://localhost:8000/___graphql
Please share your gatsby-config.js screen, the gatsby-source-strapi section.
this could be caused by the collectionTypes/singleTypes in the gatsby-source-strapi, or your USERS & PERMISSIONS PLUGIN (roles) in strapi is not set
I've changed contentTypes to collectionTypes
Also there is a new version (v4) of strapi and to make gatsby work with this new version, you need to use the following gatsby-source plugin.
npm install --save gatsby-source-strapi#relate-app/gatsby-source-strapi
This plugin wants a token which you can create at http://localhost:1337/admin/settings/api-tokens
before testing the new plugin make sure to clean out your gatsby cache by using the following command:
gatsby clean
{
resolve: "gatsby-source-strapi",
options: {
apiURL: "http://localhost:1337",
collectionTypes: ["Article", "User", 'Test'],
// Extract images from markdown fields.
markdownImages: {
typesToParse: {
Article: ["body"],
ComponentBlockBody: ["text"],
},
},
// Only include specific locale.
locale: "en", // default to all
// Include drafts in build.
preview: true, // defaults to false
// Use application token.
token:
'Your-strapi-api-token',
// Add additional headers.
headers: {},
},
},
There has also been a article about a new plugin, but this refers to another one which didn't work for me.
https://strapi.io/blog/introducing-the-new-gatsby-source-strapi-plugin
When added "${DOMAIN}/api" on apiURL it worked for me with strapi v4
apiURL: "http://localhost:1337/api",
{
resolve: "gatsby-source-strapi",
options: {
apiURL: "http://localhost:1337/api",
collectionTypes: [`messages`],
// Extract images from markdown fields.
markdownImages: {
typesToParse: {
Article: ["body"],
ComponentBlockBody: ["text"],
},
},
// Only include specific locale.
locale: "en", // default to all
// Include drafts in build.
preview: true, // defaults to false
// Use application token.
token: "token",
// Add additional headers.
headers: {},
},
},
This code solved my problem.
{
resolve:'gatsby-source-strapi',
options:{
apiURL:'*http://localhost:1337/admin/content-manager/collectionType/api::*',
collectionTypes: ['propiedads','paginas','categorias'],
queryLimit:1000
}
}

service worker registered when serving locally, but doesn't work online

I built a PWA with Vue, and for some reason when I try and deploy it online, I get this error message in the console:
service-worker.js:168
Uncaught (in promise) Error: Request for https://example.com/dist/service-worker.js?_sw-precache=935625ad5331efd775a1f6b37f06e3e3 returned a response with status 404
at https://example.com/service-worker.js:168:25
at async Promise.all (index 1)
I'm thinking that the problem is that service-worker.js is being fetched from example.com/dist/service-worker.js, which does throw a 404 error when I try to access it. The right path is example.com/service-worker.js.
I am using render.com for my hosting and I've set the Publish Directory to /dist, since that's where the built files are outputted.
This is the content of registerServiceWorker.js:
/* eslint-disable no-console */
import { register } from 'register-service-worker'
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready() {
console.log(
'App is being served from cache by a service worker.'
)
},
registered() {
console.log('Service worker has been registered.')
},
cached() {
console.log('Content has been cached for offline use.')
},
updatefound() {
console.log('New content is downloading.')
},
updated() {
console.log('New content is available; please refresh.')
},
offline() {
console.log('No internet connection found. App is running in offline mode.')
},
error(error) {
console.error('Error during service worker registration:', error)
}
})
}
When I build and serve the app locally, it works fine, and I can install it without any problems. I don't know how I can change things so the service worker is fetched from example.com/service-worker.js instead of example.com/dist/service-worker.js, which is an invalid path.But I'm not an expert on this so I'm not sure if this is even the problem.
I used sw-precache to generate the service worker.
I have looked at other questions with similar titles, but most of the comments or answers say to use HTTPS otherwise it won't work, but I am using HTTPS, so they don't solve my problem.
Thanks in advance
I used workbox to generate my service worker and it works fine now.
https://developers.google.com/web/tools/workbox
// workbox-config.js
module.exports = {
"globDirectory": "dist/",
"globPatterns": [
"**/*.{css,ico,svg,png,xml,html,js,json,txt}"
],
"swDest": "public/sw.js"
};
// vue.config.js
const {GenerateSW} = require('workbox-webpack-plugin');
module.exports = {
pwa: {
name: 'Name',
themeColor: '#fff',
msTileColor: '#fff',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
// configure the workbox plugin
workboxPluginMode: 'GenerateSW',
workboxOptions: {
swDest: 'sw.js',
}
}
}

PrerenderIO not working on my MeteorApp

I have an Issue with making PrerenderIO work on my app.
I am running meteor#1.3.5.1 and prerender-node and I have set up this code in my server/prerenderio.js like this
Meteor.startup( function(){
const prerenderio = Npm.require('prerender-node');
const settings = Meteor.settings.PrerenderIO;
console.log(settings);
if (settings && settings.token && settings.host) {
console.log('This is true');
prerenderio.set('prerenderToken', settings.token);
prerenderio.set('host', settings.host);
prerenderio.set('protocol', 'http');
WebApp.rawConnectHandlers.use(prerenderio);
}
});
And my settings.json liiks like this
{
"PrerenderIO": {
"token": "wi7DqaiBlaBlaBlaqTGmT",
"host": "http://locallhost:3000/"
},
"public":{
"ga": {
"id": "UA-XXXXXXXXX-1"
}
}
}
When I start the server on my localhost, I get this on the log
Prerender Token: wi7DqaiBlaBlaBlaqTGmT
So, I have PrerenderIO's local server running on port:3033 and when I run http://localhost:3000/?_escaped_fragment_=, it takes long and then returns "localhost not found" and logs some error on my meteor server logs.
Also, when I deploy the app to my host, and the visit my prerender.io dashboard I still see the warning that i have not installed my prerender token.
when I visit http://localhost:3033/http://localhost:3000 I get the cached page without the images
Please NOTE i have tried the following packages dfischer:prerenderio and dferber:prerenderbut the same thing.
Somewhere in your server, you need to import Meteor to fetch your private settings, you need to import prerenderIO from your node modules and WebApp from meteor/webapp. Setup your config file for prerender like this:
import prerenderIO from 'prerender-node';
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
Meteor.startup(() => {
const settings = Meteor.settings.private.PrerenderIO;
if (settings && settings.token && settings.host) {
prerenderIO.set('prerenderToken', settings.token);
prerenderIO.set('host', settings.host);
prerenderIO.set('protocol', 'http');
WebApp.rawConnectHandlers.use(prerenderIO);
}
});
Also, in your settings, you don't need to include http in your domain string, as you're setting it in the server by calling the protocol method. your host url should just be: localhost:3000

Categories