Meteor-Up (mup) error after "mup init" - javascript

I am trying to use mup to deploy a meteor app to my DigitalOcean droplet.
What I have done so far
Followed instructions on "Meteor-Up" website http://meteor-up.com/getting-started.html.
Installed mup via "npm install --global mup"
Created ".deploy" folder in my app directory. Ran "mup init".
Configured file "mup.js" file for my app, ran "mup setup".
Here is where I ran into an error. Upon running "mup setup", I am hit with the following error. [
What I tried:
I suspected that there could have been an issue with my syntax when configuring the mup.js file. After double-checking and not finding any error, I decided to re-install mup, and try running "mup setup" without modifying the "mup.js" file. However, I still receive the same error message.
Furthermore, after running "mup init", I can no longer run "mup" either, as I receive the same error as seen above. I suspect therefore that the issue is with the mup.js file. I have attached the generic version provided by meteor-up below (which still causes the error seen above).
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '1.2.3.4',
username: 'root',
// pem: './path/to/pem'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
},
app: {
// TODO: change app name and path
name: 'app',
path: '../app',
servers: {
one: {},
},
buildOptions: {
serverOnly: true,
},
env: {
// TODO: Change to your app's url
// If you are using ssl, it needs to start with https://
ROOT_URL: 'http://app.com',
MONGO_URL: 'mongodb://localhost/meteor',
},
// ssl: { // (optional)
// // Enables let's encrypt (optional)
// autogenerate: {
// email: 'email.address#domain.com',
// // comma separated list of domains
// domains: 'website.com,www.website.com'
// }
// },
docker: {
// change to 'abernix/meteord:base' if your app is using Meteor 1.4 - 1.5
image: 'abernix/meteord:node-8.4.0-base',
},
// Show progress bar while uploading bundle to server
// You might need to disable it on CI servers
enableUploadProgressBar: true
},
mongo: {
version: '3.4.1',
servers: {
one: {}
}
}
};
Any help would be greatly appreciated!
Thank you

The error dialog you posted shows a syntax error at line 10, character 5.
If you take a look:
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '1.2.3.4',
username: 'root',
// pem: './path/to/pem'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
^^^ This character
},
It's a closing brace which JS was not expecting. So why was it unexpected, lets move back to the last valid syntax:
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '1.2.3.4',
username: 'root',
^^^ This character
// pem: './path/to/pem'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
},
Well, looks like a comma which isn't followed by another key-value pair. Also known as a syntax error.
Take the comma out and things should be fine again!

I faced this same issue today. The problem is that Windows is trying to execute the mup.js file as a JScript script.
Here is the solution from the Meteor Up Common Problems page:
Mup silently fails, mup.js file opens instead, or you get a Windows script error
If you are using Windows, make sure you run commands with mup.cmd instead of mup , or use PowerShell.
That is, instead of mup setup, run mup.cmd setup.

Related

Codeceptjs: I got ERROR webdriver: Request failed with status 404 due to unknown command when trying to click to an mobile element

When I tried to click an element using Appium and Codeceptjs, I got the error below:
ERROR webdriver: Request failed with status 404 due to unknown command: The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.
Full log below:
-- FAILURES:
1) login
test something:
The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource
at getErrorFromResponseBody (C:\Users\DELL\node_modules\webdriver\build\utils.js:197:12)
at NodeJSRequest._request (C:\Users\DELL\node_modules\webdriver\build\request\index.js:158:60)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Browser.wrapCommandFn (C:\Users\DELL\node_modules\#wdio\utils\build\shim.js:137:29)
Scenario Steps:
- I.click("//android.widget.Button[#content-desc="Login"]/android.widget.TextView[2]") at Test.<anonymous> (.\login_test.js:9:7)
- I.seeAppIsInstalled("com.wdiodemoapp") at Test.<anonymous> (.\login_test.js:8:7)
This error log appears when the codeceptjs call I.click() api I think. I tried use Accesibility ID and Xpath to get element but get the same error
My test code:
Feature('login');
const LOGIN_ICON = '~Login'
const LOGIN_BTN = '~button-LOGIN'
const EMAIL_TXT_FIELD = '~input-email'
const PASSWORD_TXT_FIELD = '~input-password'
Scenario('test something', ({ I }) => {
I.seeAppIsInstalled("com.wdiodemoapp")
I.click('//android.widget.Button[#content-desc="Login"]/android.widget.TextView[2]')
I.fillField(EMAIL_TXT_FIELD, "abc")
I.fillField(PASSWORD_TXT_FIELD, "12345678")
I.click(LOGIN_BTN)
});
Below are my config file:
exports.config = {
tests: './*_test.js',
output: './output',
helpers: {
Appium: {
platform: 'Android',
device: 'emulator',
desiredCapabilities: {
appPackage: "com.wdiodemoapp",
appActivity: "MainActivity",
deviceName: "emulator-5554",
platformName: "Android",
automationName: "UiAutomator2",
}
}
},
include: {
I: './steps_file.js'
},
bootstrap: null,
mocha: {},
name: 'codecept-mobile-auto'
}
Any idea please !!! I am the new to codeceptjs testing tool
Thank a lot
I had two things I had to do to fix this issue:
I needed the platform to be set to 'android' instead of 'Android'. It looks like codecept does a case sensitive check on whether to run the Touch click or Element click. If I'm reading the code right, you can see it in this line from their WebDriver.js file.
const clickMethod = this.browser.isMobile && this.browser.capabilities.platformName !== 'android' ? 'touchClick' : 'elementClick';
If you look through the Appium calls, this changes the API from /touch/click to /element/:elementid/click which works correctly.
Not sure if this was necessary, but I did run an npm update / npm install to refresh all of my packages. This was after updating to the latest version of appium.
Hope this helps and someone else doesn't have to beat their head against this wall.

How to move from Firebase Functions to Cloud Run after encountering 540s timeout limit?

I was reading this Reddit thread where a user mentioned that 540s is the limit of Firebase Functions and that moving to Cloud Run was recommended.
As others have said 540s is the maximum timeout and if you want to increase it without changing much else about your code, consider moving to Cloud Run. ​- #samtstern on Reddit
After looking at the Node.JS QuickStart documentation
and other content on YouTube and Google, I did not find a good guide explaining how to move your Firebase Function to Cloud Run.
One of the issues that were not addressed by what I read, for example: what do I replace the firebase-functions package with to define the function? Etc...
So, how may I move my Firebase Function over to Cloud Run to not run into the 540s max timeout limitation ?
​const functions = require('firebase-functions');
​const runtimeOpts = {timeoutSeconds: 540,memory: '2GB'}
​exports.hourlyData = functions.runWith(runtimeOpts).pubsub.schedule('every 1 hours')
Preface: The following steps have been generalized for a wider audience than just the OP's problem (covers HTTP Event, Scheduled and Pub/Sub Functions) and have been adapted from the documentation linked in the question: Deploying Node.JS Images on Cloud Run.
Step 0: Code/Architecture Review
More often than not, exceeding the 9-minute timeout of a Cloud Function is a result of a bug in your code - make sure to evaluate this before switching to Cloud Run as this will just make the problem worse. The most common of these is sequential instead of parallelized asynchronous processing (normally caused by using await in a for/while loop).
If your code is doing meaningful work that is taking a long time, consider sharding it out to "subfunctions" that can all work on the input data in parallel. Instead of processing data for every user in your database, you can use a single function to trigger multiple instances of a function that each that take care of different user ID ranges such as a-l\uf8ff, m-z\uf8ff, A-L\uf8ff, M-Z\uf8ff and 0-9\uf8ff.
Lastly, Cloud Run and Cloud Functions are quite similar, they are designed to take a request, process it and then return a response. Cloud Functions have a limit of up to 9 minutes and Cloud Runs have a limit of up to 60 minutes. Once that response has been completed (because the server ended the response, the client lost connection or the client aborted the request), the instance is severely throttled or terminated. While you can use WebSockets and gRPC for a persistent communication between server and client when using Cloud Run, they are still subject to this limitation. See the Cloud Run: General development tips documentation for more information.
Like other serverless solutions, your client and server need to be able to handle connecting to different instances. Your code shouldn't make use of local state (like a local store for session data). See the Setting request timeout documentation for more information.
Step 1: Install Google Cloud SDK
I'll refer you to the Installing Google Cloud SDK documentation for this step.
Once installed, call gcloud auth login and login with the account used for the target Firebase project.
Step 2: Get your Firebase Project settings
Open up your project settings in the Firebase Console and take note of your Project ID and your Default GCP resource location.
Firebase Functions and Cloud Run instances should be co-located with your GCP resources where possible. In Firebase Functions, this is achieved by changing the region in code and deploying using the CLI. For Cloud Run, you specify these parameters on the command line as flags (or use the Google Cloud Console). For the below instructions and for simplicity, I will be using us-central1 as my Default GCP resources location is nam5 (us-central).
If using the Firebase Realtime Database in your project, visit your RTDB settings in the Firebase Console and take note of your Database URL. This is usually of the form https://PROJECT_ID.firebaseio.com/.
If using Firebase Storage in your project, visit your Cloud Storage settings in the Firebase Console and take note of your Bucket URI. From this URI, we need to take note of the host (ignore the gs:// part) which is usually of the form PROJECT_ID.appspot.com.
Here's a table that you can copy to help keep track:
Project ID:
PROJECT_ID
Database URL:
https://PROJECT_ID.firebaseio.com
Storage Bucket:
PROJECT_ID.appspot.com
Default GCP Resource Location:
Chosen Cloud Run Region:
Step 3: Create Directories
In your Firebase Project directory or a directory of your choosing, create a new cloudrun folder.
Unlike Firebase Cloud Functions, where you can define multiple functions in a single module of code, each Cloud Run image uses its own module of code. For this reason, each Cloud Run image should be stored in its own directory.
As we are going to define a Cloud Run instance called helloworld, we'll create a directory called helloworld inside cloudrun.
mkdir cloudrun
mkdir cloudrun/helloworld
cd cloudrun/helloworld
Step 4: Create package.json
For correct deployment of the Cloud Run image, we need to provide a package.json that is used to install dependencies in the deployed container.
The format of the package.json file resembles:
{
"name": "SERVICE_NAME",
"description": "",
"version": "1.0.0",
"private": true,
"main": "index.js",
"scripts": {
"start": "node index.js"
"image": "gcloud builds submit --tag gcr.io/PROJECT_ID/SERVICE_NAME --project PROJECT_ID",
"deploy:public": "gcloud run deploy SERVICE_NAME --image gcr.io/PROJECT_ID/SERVICE_NAME --allow-unauthenticated --region REGION_ID --project PROJECT_ID",
"deploy:private": "gcloud run deploy SERVICE_NAME --image gcr.io/PROJECT_ID/SERVICE_NAME --no-allow-unauthenticated --region REGION_ID --project PROJECT_ID",
"describe": "gcloud run services describe SERVICE_NAME --region REGION_ID --project PROJECT_ID --platform managed",
"find": "gcloud run services describe SERVICE_NAME --region REGION_ID --project PROJECT_ID --platform managed --format='value(status.url)'"
},
"engines": {
"node": ">= 12.0.0"
},
"author": "You",
"license": "Apache-2.0",
"dependencies": {
"express": "^4.17.1",
"body-parser": "^1.19.0",
/* ... */
},
"devDependencies": {
/* ... */
}
}
In the above file, SERVICE_NAME, REGION_ID and PROJECT_ID are to be swapped out as appropriate with the details from step 2. We also install express and body-parser to handle the incoming request.
There are also a handful of module scripts to help with deployment.
Script Name
Description
image
Submits the image to Cloud Build to be added to the Container Registry for other commands.
deploy:public
Deploys the image from the above command to be used by Cloud Run (while allowing any requester to invoke it) and returns its service URL (which is partly randomized).
deploy:private
Deploys the image from the above command to be used by Cloud Run (while requiring that the requester that invokes it is an authorized user/service account) and returns its service URL (which is partly randomized).
describe
Gets the statistics & configuration of the deployed Cloud Run.
find
Extracts only the service URL from the response of npm run describe
Note: Here, "Authorized User" refers to a Google Account associated with the project, not an ordinary Firebase User. To allow a Firebase User to invoke your Cloud Run, you must deploy it using deploy:public and handle token validation in your Cloud Run's code, rejecting requests appropriately.
As an example of this file filled in, you get this:
{
"name": "helloworld",
"description": "Simple hello world sample in Node with Firebase",
"version": "1.0.0",
"private": true,
"main": "index.js",
"scripts": {
"start": "node index.js"
"image": "gcloud builds submit --tag gcr.io/com-example-cloudrun/helloworld --project com-example-cloudrun",
"deploy:public": "gcloud run deploy helloworld --image gcr.io/com-example-cloudrun/helloworld --allow-unauthenticated --region us-central1 --project com-example-cloudrun",
"deploy:public": "gcloud run deploy helloworld --image gcr.io/com-example-cloudrun/helloworld --no-allow-unauthenticated --region us-central1 --project com-example-cloudrun",
"describe": "gcloud run services describe helloworld --region us-central1 --project com-example-cloudrun --platform managed",
"find": "gcloud run services describe helloworld --region us-central1 --project com-example-cloudrun --platform managed --format='value(status.url)'"
},
"engines": {
"node": ">= 12.0.0"
},
"author": "You",
"license": "Apache-2.0",
"dependencies": {
/* ... */
},
"devDependencies": {
/* ... */
}
}
Step 5: Create your container files
To tell Cloud Build what container to use for your Cloud Run image, you must create a Dockerfile for your image. To prevent sending the wrong files to the server, you should also specify a .dockerignore file.
In this file, we use the Firebase Project settings from Step 2 to recreate the process.env.FIREBASE_CONFIG environment variable. This variable is used by the Firebase Admin SDK and contains the following information as a JSON string:
{
databaseURL: "https://PROJECT_ID.firebaseio.com",
storageBucket: "PROJECT_ID.appspot.com",
projectId: "PROJECT_ID"
}
Here is cloudrun/helloworld/Dockerfile:
# Use the official lightweight Node.js 14 image.
# https://hub.docker.com/_/node
FROM node:14-slim
# Create and change to the app directory.
WORKDIR /usr/src/app
# Copy application dependency manifests to the container image.
# A wildcard is used to ensure copying both package.json AND package-lock.json (when available).
# Copying this first prevents re-running npm install on every code change.
COPY package*.json ./
# Install production dependencies.
# If you add a package-lock.json, speed your build by switching to 'npm ci'.
# RUN npm ci --only=production
RUN npm install --only=production
# Copy local code to the container image.
COPY . ./
# Define default configuration for Admin SDK
# databaseURL is usually "https://PROJECT_ID.firebaseio.com", but may be different.
# TODO: Update me
ENV FIREBASE_CONFIG={"databaseURL":"https://PROJECT_ID.firebaseio.com","storageBucket":"PROJECT_ID.appspot.com","projectId":"PROJECT_ID"}
# Run the web service on container startup.
CMD [ "node", "index.js" ]
Here is cloudrun/helloworld/.dockerignore:
Dockerfile
.dockerignore
node_modules
npm-debug.log
Step 6: Create & deploy your entry point
When a new Cloud Run instance is launched, it will normally specify the port it wants your code to listen on using the PORT environment variable.
Variant: Migrating a HTTP Event Function
When you use a HTTP Event function from the firebase-functions package, it internally handles body-parsing on your behalf. The Functions Framework uses the body-parser package for this and defines the parsers here.
To handle user authorization, you could use this validateFirebaseIdToken() middleware to check the ID token given with the request.
For a HTTP-based Cloud Run, configuring CORS will be required to invoke it from a browser. This can be done by installing the cors package and configuring it appropriately. In the below sample, cors will reflect the origin sent to it.
const express = require('express');
const cors = require('cors')({origin: true});
const app = express();
app.use(cors);
// To replicate a Cloud Function's body parsing, refer to
// https://github.com/GoogleCloudPlatform/functions-framework-nodejs/blob/d894b490dda7c5fd4690cac884fd9e41a08b6668/src/server.ts#L47-L95
// app.use(/* body parsers */);
app.enable('trust proxy'); // To respect X-Forwarded-For header. (Cloud Run is behind a load balancer proxy)
app.disable('x-powered-by'); // Disables the 'x-powered-by' header added by express (best practice)
// Start of your handlers
app.get('/', (req, res) => {
const name = process.env.NAME || 'World';
res.send(`Hello ${name}!`);
});
// End of your handlers
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`helloworld: listening on port ${port}`);
});
In the $FIREBASE_PROJECT_DIR/cloudrun/helloworld directory, execute the following commands to deploy your image:
npm run image // builds container & stores to container repository
npm run deploy:public // deploys container image to Cloud Run
Variant: Invoke using Cloud Scheduler
When invoking a Cloud Run using the Cloud Scheduler, you can choose which method is used to invoke it (GET, POST (the default), PUT, HEAD, DELETE). To replicate a Cloud Function's data and context parameters, it is best to use POST as these will then be passed in the body of the request. Like Firebase Functions, these requests from Cloud Scheduler may be retried so make sure to handle idempotency appropriately.
Note: Even though the body of a Cloud Scheduler invocation request is JSON-formatted, the request is served with Content-Type: text/plain, which we need to handle.
This code has been adapted from the Functions Framework source (Google LLC, Apache 2.0)
const express = require('express');
const { json } = require('body-parser');
async function handler(data, context) {
/* your logic here */
const name = process.env.NAME || 'World';
console.log(`Hello ${name}!`);
}
const app = express();
// Cloud Scheduler requests contain JSON using
"Content-Type: text/plain"
app.use(json({ type: '*/*' }));
app.enable('trust proxy'); // To respect X-Forwarded-For header. (Cloud Run is behind a load balancer proxy)
app.disable('x-powered-by'); // Disables the 'x-powered-by' header added by express (best practice)
app.post('/*', (req, res) => {
const event = req.body;
let data = event.data;
let context = event.context;
if (context === undefined) {
// Support legacy events and CloudEvents in structured content mode, with
// context properties represented as event top-level properties.
// Context is everything but data.
context = event;
// Clear the property before removing field so the data object
// is not deleted.
context.data = undefined;
delete context.data;
}
Promise.resolve()
.then(() => handler(data, context))
.then(
() => {
// finished without error
// the return value of `handler` is ignored because
// this isn't a callable function
res.sendStatus(204); // No content
},
(err) => {
// handler threw error
console.error(err.stack);
res.set('X-Google-Status', 'error');
// Send back the error's message (as calls to this endpoint
// are authenticated project users/service accounts)
res.send(err.message);
}
)
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`helloworld: listening on port ${port}`);
});
Note: The Functions Framework handles errors by sending back a HTTP 200 OK response with a X-Google-Status: error header. This effectively means "failed successfully". As an outsider, I'm not sure why this is done but I can assume it's so that the invoker knows to not bother retrying the function - it'll just get the same result.
In the $FIREBASE_PROJECT_DIR/cloudrun/helloworld directory, execute the following commands to deploy your image:
npm run image // builds container & stores to container repository
npm run deploy:private // deploys container image to Cloud Run
Note: In the following setup commands (only need to run these once), PROJECT_ID, SERVICE_NAME, SERVICE_URL and IAM_ACCOUNT will need to be substituted as appropriate.
Next we need to create a service account that Cloud Scheduler can use to invoke the Cloud Run. You can call it whatever you want such as scheduled-run-invoker. The email of this service account will be referred to as IAM_ACCOUNT in the next step. This Google Cloud Tech YouTube video (starts at the right spot, about 15s) will quickly show what you need to do. Once you've created the account, you can create the Cloud Scheduler job following the next 30 or so seconds of the video or use the following command:
gcloud scheduler jobs create http scheduled-run-SERVICE_NAME /
--schedule="every 1 hours" /
--uri SERVICE_URL /
--attempt-deadline 60m /
--http-method post /
--message-body='{"optional-custom-data":"here","if-you":"want"}' /
--oidc-service-account-email IAM_ACCOUNT
--project PROJECT_ID
Your Cloud Run should now be scheduled.
Variant: Invoke using Pub/Sub
To my understanding, the deploy process is the same as for a scheduled run (deploy:private) but I'm unsure about the specifics. However, here is the Cloud Run source for a Pub/Sub parser:
This code has been adapted from the Functions Framework source (Google LLC, Apache 2.0)
const express = require('express');
const { json } = require('body-parser');
const PUBSUB_EVENT_TYPE = 'google.pubsub.topic.publish';
const PUBSUB_MESSAGE_TYPE =
'type.googleapis.com/google.pubsub.v1.PubsubMessage';
const PUBSUB_SERVICE = 'pubsub.googleapis.com';
/**
* Extract the Pub/Sub topic name from the HTTP request path.
* #param path the URL path of the http request
* #returns the Pub/Sub topic name if the path matches the expected format,
* null otherwise
*/
const extractPubSubTopic = (path: string): string | null => {
const parsedTopic = path.match(/projects\/[^/?]+\/topics\/[^/?]+/);
if (parsedTopic) {
return parsedTopic[0];
}
console.warn('Failed to extract the topic name from the URL path.');
console.warn(
"Configure your subscription's push endpoint to use the following path: ",
'projects/PROJECT_NAME/topics/TOPIC_NAME'
);
return null;
};
async function handler(message, context) {
/* your logic here */
const name = message.json.name || message.json || 'World';
console.log(`Hello ${name}!`);
}
const app = express();
// Cloud Scheduler requests contain JSON using
"Content-Type: text/plain"
app.use(json({ type: '*/*' }));
app.enable('trust proxy'); // To respect X-Forwarded-For header. (Cloud Run is behind a load balancer proxy)
app.disable('x-powered-by'); // Disables the 'x-powered-by' header added by express (best practice)
app.post('/*', (req, res) => {
const body = req.body;
if (!body) {
res.status(400).send('no Pub/Sub message received');
return;
}
if (typeof body !== "object" || body.message === undefined) {
res.status(400).send('invalid Pub/Sub message format');
return;
}
const context = {
eventId: body.message.messageId,
timestamp: body.message.publishTime || new Date().toISOString(),
eventType: PUBSUB_EVENT_TYPE,
resource: {
service: PUBSUB_SERVICE,
type: PUBSUB_MESSAGE_TYPE,
name: extractPubSubTopic(req.path),
},
};
// for storing parsed form of body.message.data
let _jsonData = undefined;
const data = {
'#type': PUBSUB_MESSAGE_TYPE,
data: body.message.data,
attributes: body.message.attributes || {},
get json() {
if (_jsonData === undefined) {
const decodedString = Buffer.from(base64encoded, 'base64')
.toString('utf8');
try {
_jsonData = JSON.parse(decodedString);
} catch (parseError) {
// fallback to raw string
_jsonData = decodedString;
}
}
return _jsonData;
}
};
Promise.resolve()
.then(() => handler(data, context))
.then(
() => {
// finished without error
// the return value of `handler` is ignored because
// this isn't a callable function
res.sendStatus(204); // No content
},
(err) => {
// handler threw error
console.error(err.stack);
res.set('X-Google-Status', 'error');
// Send back the error's message (as calls to this endpoint
// are authenticated project users/service accounts)
res.send(err.message);
}
)
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`helloworld: listening on port ${port}`);
});

(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
}
}

Ember 3.6 super-rentals tutorial LEAFLET_MAPS_API_KEY using environment.js

While going through the ember 3.6 super-rentals tutorial I ran into a few snags adding the ember-simple-leaflet-maps.
I couldn't get the environment variable LEAFLET_MAPS_API_KEY to set.
https://guides.emberjs.com/release/tutorial/service/
To my understanding, the tutorial has you set an environment variable on your operating system? Maybe I'm wrong in thinking that, but I wanted a way to just add the variable to my project /config/environment.js
Answer from OP:
After the addon was installed:
ember install ember-simple-leaflet-maps
I opened the geocode.js file to see how the service was injecting the api key. Path is:
node_modules\ember-simple-leaflet-maps\addon\services\geocode.js
The line of code was:
let accessToken = getOwner(this).resolveRegistration('config:environment')['ember-simple-leaflet-maps'].apiKey;
From there I just added the lookup it was looking for to my file /config/environment.js
let ENV = {
modulePrefix: 'super-rentals',
environment,
rootURL: '/',
locationType: 'auto',
'ember-simple-leaflet-maps': {
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
Rebuild the project and serve, my maps are now showing up
ember build
ember serve

nodejs - error self signed certificate in certificate chain

I am facing a problem with client side https requests.
A snippet can look like this:
var fs = require('fs');
var https = require('https');
var options = {
hostname: 'someHostName.com',
port: 443,
path: '/path',
method: 'GET',
key: fs.readFileSync('key.key'),
cert: fs.readFileSync('certificate.crt')
}
var requestGet = https.request(options, function(res){
console.log('resObj', res);
}
What I get is Error: self signed certificate in certificate chain.
When I use Postman I can import the client certificate and key and use it without any problem. Is there any solution available?? I would also like to be given some lights on how postman handles the certificates and works.
Option 1: Disable the warning (useful for dev)
From your question I'm guessing you are doing this in development as you are using a self signed certificate for SSL communication.
If that's the case, add as an environment variable wherever you are running node
export NODE_TLS_REJECT_UNAUTHORIZED='0'
node app.js
or running node directly with
NODE_TLS_REJECT_UNAUTHORIZED='0' node app.js
This instructs Node to allow untrusted certificates (untrusted = not verified by a certificate authority)
If you don't want to set an environment variable or need to do this for multiple applications npm has a strict-ssl config you set to false
npm config set strict-ssl=false
Option 2: Load in CA cert, like postman (useful for testing with TLS)
If you have a CA cert already like the poster #kDoyle mentioned then you can configure in each request (thanks #nic ferrier).
let opts = {
method: 'GET',
hostname: "localhost",
port: listener.address().port,
path: '/',
ca: fs.readFileSync("cacert.pem")
};
https.request(opts, (response) => { }).end();
Option 3: Use a proper SSL Cert from a trusted source (useful for production)
letsencrypt.org is free, easy to set up and the keys can be automatically rotated. https://letsencrypt.org/docs/
You can fix this issue using NODE_TLS_REJECT_UNAUTHORIZED=0 in the terminal or inserting the following line within the JS file.
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
Beware that this a hack and it should not be used in production.
If you are using windows then run the following command in the command prompt:
set NODE_TLS_REJECT_UNAUTHORIZED=0
After that, npm install <my-package> will work.
for Nodemailer:
adding
tls: {
rejectUnauthorized: false
}
solved my problem.
Overall code looks liek this:
nodemailer.createTransport({
host: process.env.MAIL_SERVER,
secure: false,
port: 587,
auth: {
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD
},
tls: {
rejectUnauthorized: false
}
}
You can write command npm config set strict-ssl false
you just add at the start of your code this line:
process.env.NODE_TLS_REJECT_UNAUTHORIZED='0'
And everything solved, but in any case it is not recommendable, I am investigating the solution of https://letsencrypt.org/
Turning off verification is quite a dangerous thing to do. Much better to verify the certificate.
You can pull the Certificate Authority certificate into the request with the ca key of the options object, like this:
let opts = {
method: 'GET',
hostname: "localhost",
port: listener.address().port,
path: '/',
ca: await fs.promises.readFile("cacert.pem")
};
https.request(opts, (response) => { }).end();
I put a whole demo together of this so you can see how to construct SSL tests.
It's here.
Do:
Better use this if running a node script for standalone purpose,
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
Don't:
instead of changing all default request process.
npm config set strict-ssl=false
i.e., don't alter your node config, else it will apply to all your requests, by making it default config. So just use it where necessary.
The node application needs to have the CA certificate added to the existing CA (Mozilla) certificates.
We start node using a service, and add the environment variable, NODE_EXTRA_CA_CERTS
[Service]
Restart=always
User=<...>
Group=<...>
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
Environment=NODE_EXTRA_CA_CERTS=/<...>/.ssl/extra_certs.pem
WorkingDirectory=/<...>
ExecStart=/usr/bin/node -r dotenv/config /<.....>/server.js dotenv_config_path=/<....>/.env
This way we can use the same application to call services using popular CAs or our own self signed certs, and we don't have to turn off SSL checking.
In linux there is an easy way to get the certificate, use this post: Use self signed certificate with cURL?
You create your certificate using:
$ echo quit | openssl s_client -showcerts -servername server -connect server:443 > cacert.pem
then copy that .pem file as the extra_cert.pem. You can only have one pem file, but you can append multiple pem files into one file.
I hope this helps someone, it took me a while to find the different parts to make this work.
For what it's worth, after spending a day and a half trying to track this one down it turned out the error was caused by a setting on my company's firewall that IT had to disable. Nothing anywhere on the internet did anything to fix this.
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0; Even though its not worked ...
Not Able to Install Cypress:
S C:\Cypress> export NODE_TLS_REJECT_UNAUTHORIZED='0' node app.js
export : The term 'export' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At line:1 char:1
export NODE_TLS_REJECT_UNAUTHORIZED='0' node app.js
+ CategoryInfo : ObjectNotFound: (export:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Categories