I'm having an issue setting the $axios base URL for my api endpoint within my Nuxt app.
I'm using the dotENV module and I have this setting in it:
BASE_URL=http://localhost:3000/api2
In my nuxt.config.js file I have:
axios: {
baseURL: process.env.BASE_URL,
},
This doesn't work for whatever reason. If I hardcode it and try:
axios: {
baseURL: 'http://localhost:3000/api2',
},
it works fine.
Anyone know why this isn't working?
Related
I'm using scully for prerendering bunch of routes, and I skip routes for /board/:boardId:
routes: {
"/board": {
type: 'ignored'
}
},
extraRoutes: ["/",
"/dashboard",
"/uses"
]
The /board route is dynamic, i.e. it looks like /board/[user-generated-boardId], but when I navigate to it using npx scully serve, It breaks, e.g.
I don't want to prerender /board/:boardId routes, and they should work just like an angular SPA, but seems like scully server is trying to map them to a directory path within dist.
Any suggestion on how I can get both static and dynamic routes working with scully, would be great ! Thanks.
When Scully can not find a route it should default to the expected Angular client side rendered page generation. To take advantage of some of the benefits of static pages and Scully you could generated a base page for dynamic routes tell Scully to ignore the remainder of the dynamic route.
Example is turning this routing-module path:
const routes: Routes = [
{ path: 'stuff/:id', component: StuffComponent },
];
Into two routes where one is generated and the other is ignored:
const routes: Routes = [
{ path: 'stuff', component: StuffComponent },
{ path: 'stuff/:id', component: StuffComponent },
];
Don't forget to ignore the dynamic route in your scully.app-name.config.ts
export const config: ScullyConfig = {
projectRoot: './src',
projectName: 'app-name',
outDir: './dist/static',
routes: {
'/stuff/:id': {
type: 'ignored',
},
},
};
If you need to turn OFF or ON specific content when either running or generating utilize Scully's 2 utility methods isScullyRunning() & isScullyGenerated()
WARNING
By design the Scully dev server WILL NOT LOAD DYNAMIC ROUTES. That is, if you follow the above approach npx scully serve will still result in the Cannot GET ... error. You will have to use a fully featured server to run to see the results. For example in your terminal:
cd dist/static
npx http-server
You defined a route for /board which will exclude that route.
However, you did not define a route for /board/:boardId so Scully will try to render that route.
Amend your config like this:
"/board": {
type: 'ignored'
},
"/board/:boardId": {
type: 'ignored'
}
},
That will likely solve your issue.
For the other part of your question, Scully will try to match the routes it found during discovery by default. This is done so you will be alarmed during testing that this route isn't there. After all, the Scully server is a development, not a deployment tool.
If you need/want to serve the index.html on routes not found, you can use the 404 option.
You can add that to your CMD line like this:
npx scully serve --404=index
By doing that, Scully will serve the index.html on any route that is not pre-rendered.
The answer is for firebase hosting, but should apply more generally.
As I'm using firebase hosting, I solved it using firebase hosting config within my project's firebase.json:
{
"hosting: [
{
"target": "static",
"public": "dist/static",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "/dashboard/**",
"destination": "/dashboard/index.html"
},
{
"source": "/uses/**",
"destination": "/uses/index.html"
},
{
"source": "**",
"destination": "/index.html"
}
]
}
]
}
This config dictates that dashboard and uses routes should map to specific folder paths, and rest should map to index.html in the root directory.
Reference: https://firebase.google.com/docs/hosting/full-config
==
P.S. My local server with npx scully serve still can't load those dynamic /board/** routes, but at least it works when deployed to firebase. Suggestions very welcome!!
I'm actually trying to use nuxt-mail in a personnal project,
During my development phase, I receive all my testing mails. And from there I did the following adjustments to do the exact same request from my builded site :
//nuxt.config.js
env: {
baseUrl:
process.env.NODE_ENV === 'dev'
? 'http://localhost:3000'
: 'https://my-domain.netlify.app'
},
My code when using the 'send' function :
this.$axios.$post(process.env.baseUrl + "/mail/send", {
config: 'contact',
from: document.getElementById('input-2').value,
subject: document.getElementById('subject').value,
text: "This is a text message",
})
It continues to work well with localhost/3000/mail/send but I have a 404 error once I build my site and using https:/ /my-domain.netlify.app/mail/send :
POST https://my-domain.netlify.app/mail/send [HTTP/2 404 Not Found 186ms]
Uncaught (in promise) Error: Request failed with status code 404
I'm actually struggling to solve this problem, am I missing something ?
Alright, so if your target is static, you can only do yarn generate.
If you do have the default, aka target: server, you can only yarn build.
Then, as talked about it a bit here: Sending mail in Nuxt.js with nuxt-mail
You cannot use a Node.js package in a static environment, so neither yarn generate nor Netlify will help you here. You need to yarn build and host it on something like Heroku.
One last step that you can do, is to try it locally with the following:
target: server
yarn build
yarn start
make your POST call with Postman or alike
If it does not work here, it is a code issue and you can look into the hosting one.
If it does work locally, you can proceed to the hosting issue that you'll face.
Well you just misunderstood the env field in the nuxt.config.js file.
That env field is passed to the $config Object of the Nuxt App and not passed to process.env.
What you want is to set the BaseUrl for the Axios Module
// nuxt.config.js
axios: {
baseURL: process.env.NODE_ENV === 'dev'
? 'http://localhost:3000'
: 'https://my-domain.netlify.app'
},
// or provide a runtime config
// server and clientside
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL
}
},
// serverside only
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL
}
},
Edit:
Also when calling axios just do it like that if you implement the above changes
this.$axios.$post("/mail/send", {
// ... the rest of your code
I am new to ionic and I try to setup a proxy configuration for different environments. I have several environment-specific config files in place which get loaded using webpack and an environment variable which is set before ionic is served (see: https://github.com/gshigeto/ionic-environment-variables).
Everything works as expected but I don’t know how to solve following issue:
My proxy configuration (ionic.config.json) looks like this:
"proxies": [
{
"path": "/api",
"proxyUrl": "https://dv.mydomain.com/api",
"rejectUnauthorized": false
}
]
and one of my http calls looks like this:
return this.http.get<User[]>(ENV.apiUrl + '/api/users')
I have to remove ENV.apiUrl because otherwise the pattern specified in the proxy config doesn’t get matched, but if I do so, I cannot distinguish between different environments anymore. I have tried to add the domain to the path of the proxy configuration, which did not work.
Is there a way to solve this issue?
I asked the same question in the ionic forum but no one answered so far.
The way I "solved" it so far is not to use Ionic proxies anymore. I've installed this plugin for chrome, which basically disables chrome's CORS protection by adding Access-Control-Allow-Origin: * to the response headers.
Can't the apiUrl just be a URL path component? Ex:
// environment.pro.ts
export const environment: any = {
apiUrl: '/pro'
};
// environment.dev.ts
export const environment: any = {
apiUrl: '/dev'
};
Then, something like:
// ionic.config.json
"proxies": [
{
"path": "/pro/api",
"proxyUrl": "https://example.com/api",
"rejectUnauthorized": false
},
{
"path": "/dev/api",
"proxyUrl": "https://dev.example.com/api",
"rejectUnauthorized": false
}
]
CORS issue will only be specific to the local development as Ionic uses browser for local developement.
In mobile all the javascript will be copied as file://
Thus origin will not be exist.
So to handle this you can install the chrome extention
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
This should solve the problem.
I have an EmberJS application that uses ember-data to access data via a REST API. The REST API is running on the same machine but on a different port (although this probably applies to REST API's that are served from another domain.
When I go to the URL localhost:4200/items I get the following error in the Firefox console:
Content Security Policy: The page's settings blocked the loading of a resource at http://localhost:7654/api/items ("connect-src http://localhost:4200 ws://localhost:35729 ws://0.0.0.0:35729 http://0.0.0.0:4200").
I tried installing ember-cli-cors but nothing changed. I also tried the solution at http://discuss.emberjs.com/t/ember-data-and-cors/3690, but that didn't work either. That discussion was from 2013, so that's not a huge surprise.
The REST API is written in python using Flask and Flask-cors. Using the network tab I can see that the request is being sent, and the data being sent back, but the error is still there. The header Access-Control-Allow-Origin is set to http://localhost:4200 in the response, as expected.
app/router.js
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
export default Router.map(function() {
this.route('items');
});
app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api',
host: 'http://localhost:7654',
});
app/routes/items.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.find('item');
}
});
app/models/item.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr(),
});
app/templates/items.hbs
{{#each item in items}}
{{ item.name }}<br>
{{else}}
<p>No items</p>
{{/each}}
{{outlet}}
This is a CSP issue not CORS
Inside config/environment.js find the ENV.contentSecurityPolicy and add http://localhost:7654 to your 'connect-src' key
e.g.
ENV.contentSecurityPolicy = {
// ... other stuff here
'connect-src': "'self' http://localhost:7654"
}
You will probably need a different setting for your production environment as well.
For testing environment you can use proxy.
ember s -proxy http://localhost:7654
So all back-end request goes to your server which is running on port 7654.
I'm using Ember CLI 0.0.36. When I run ember server in my project folder, my understanding is that a server buried in some Brocoli process gets started. However I would like to program a custom Express server and have my app point to that Node.js code for its backend. How would I go about doing that within the Ember CLI framework?
UPDATE:
Following #user3155277's answer, I added an adapter file like so:
app-name/app/adapters/application.js:
import DS from 'ember-data';
export default DS.RESTAdapter.reopen({ namespace: 'api' });
I created an Express server that I put at the root of my app:
app-name/server.js:
var express = require("express"),
app = express(),
path = require("path");
app.get("/api/test", function(req, res) {
res.json({
hello: "world"
});
});
var server = app.listen(8147);
In the Ember app, my index route is defined as so:
app-name/app/routes/index.js:
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return Ember.$.getJSON("/api/test").then(function(data) {
return data;
});
}
});
On the command line I then start the server like so:
ember serve --proxy http://localhost:8147/
I get the following error:
version: 0.0.35-master-86abdb11ba
Proxying to http://localhost:8147/
object is not a functionTypeError: object is not a function
at Class.module.exports.Task.extend.start (D:\ember-cli\lib\tasks\server\express-server.js:41:43)
at Class.module.exports.Task.extend.run (D:\ember-cli\lib\tasks\serve.js:40:23)
at Class.module.exports.Command.extend.run (D:\ember-cli\lib\commands\serve.js:35:18)
at Class.Command.validateAndRun (D:\ember-cli\lib\models\command.js:74:15)
at CLI.<anonymous> (D:\ember-cli\lib\cli\cli.js:33:20)
at tryCatch (D:\ember-cli\node_modules\rsvp\dist\commonjs\rsvp\-internal.js:163:16)
at invokeCallback (D:\ember-cli\node_modules\rsvp\dist\commonjs\rsvp\-internal.js:172:17)
at publish (D:\ember-cli\node_modules\rsvp\dist\commonjs\rsvp\-internal.js:150:13)
at flush (D:\ember-cli\node_modules\rsvp\dist\commonjs\rsvp\asap.js:51:9)
at process._tickCallback (node.js:419:13)Livereload server on port 35729
This is actually pretty simple with Ember CLI 0.0.40:
Create folder structure
ember new my-app
Go into the newly created folder
cd my-app
Generate api-stub* (see update)
ember generate api-stub my-server
This latter command creates a server folder with an index.js file and a routes folder with a my-server.js file.
Open my-server.js file and you see:
module.exports = function(app) {
var express = require("express");
var myServerRouter = express.Router();
myServerRouter.get("/", function(req, res) {
res.send({my-server:"something"});
});
app.use("/api", myServerRouter);
};
All you need to do then is to change that file. If the Ember app makes calls to /api/hamsters and /api/project, edit as follows:
module.exports = function(app) {
var express = require("express");
var myServerRouter = express.Router();
myServerRouter.get("/hamsters", function(req, res) {
res.send({ ... });
});
myServerRouter.get("/project", function(req, res) {
res.send({ ... });
});
app.use("/api", myServerRouter);
};
To start the server (from project's root):
ember server
Make sure you have updated node.js to the latest version as well.
Updates
As of Ember CLI 0.0.41 (via this PR) api-stub has been renamed http-mock.
I started playing with ember cli so i'm not sure but i found the following:
https://github.com/dockyard/ember-cli-plus-backend/tree/rails-served-html/frontend/api-stub
Basically you should proxy your express server to the same port as your ember-cli (so then you don't have to deal with jsonp issue)
Set the method to 'proxy' and define the proxyURL to pass all API requests to the proxy URL.
UPDATE:
1.Generate adapter ember generate adapter application
2.Make api namespace - fill the created file with the following code:
export default DS.RESTAdapter.reopen({
namespace: 'api'
});
3.Start the server with ember serve --proxy http://localhost:1337/ (this will proxy all your request to localhost:4200 to 1337
4.Make routes in your express app prefixed by /api
Hope it helps