NuxtJs axios module global config - axios

I need to set global configuration for #nuxt/axios.
For example I need default Content-Type, Accept, Authorization header etc. and other configurations for all of my API calls. Is there any way to add these settings globally in nuxt to avoid repetition of code.

As stated here: https://axios.nuxtjs.org/extend
You can create a plugin and dump your axios configuration there like this
nuxt.config.js
export default {
plugins: [
'~/plugins/axios'
]
}
/plugins/axios.js
export default ({ $axios, $config: { baseUrlIam, secretToken } }) => {
$axios.defaults.baseURL = baseUrlIam
$axios.defaults.headers.Authorization = secretToken
}
Also, setHeader may be useful.

Related

How to set axios as a default prototype for Nuxt.js and append token to the default axios authorization header?

In Vue.js simply we can include axios as our deafault prototype for Vue.js and append local storage token to a default axios authorization header in the Vue main.js file .
As follows:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$http = axios;
const token = localStorage.getItem("token");
if(token){
Vue.prototype.$http.defaults.headers.common['Authorization'] = token;
}
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
My question is how to set axios as a default prototype for Nuxt.js and append local storage token to a default axios authorization header inside the Nuxt.config.js File
Not sure that the prototype is the way to go usually.
I do recommend this one for Nuxt
Install nuxt/axios with
yarn add #nuxtjs/axios
Then, go to your Nuxt configuration
nuxt.config.js
plugins: ['#/plugins/nuxt-axios.js'],
modules: ['#nuxtjs/axios'],
And set the configuration to your axios as you wish
/plugins/nuxt-axios.js
export default ({ $axios }, $config: { authorizationToken }) => {
$axios.defaults.headers.Authorization = authorizationToken
}
Or directly in the configuration file
nuxt.config.js
axios: {
headers: {
Authorization: process.env.TOKEN,
},
},
If you wish more info with the env variables, you can check this one: https://stackoverflow.com/a/67705541/8816585

Javascript in nuxt plugins folder - how to use in component?

I have a javascript variable (var testButton) in my Nuxt plugins folder. I then added the file to my nuxt.config.js plugins. In my component, I have a Buefy button, and I'm trying to call the script:
<b-button #click="testButton">Click Me</b-button>
...
<script>
export default {
mounted () {
this.$testButton()
}
}
</script>
I import the script in my script section and have tried computed and mounted lifecycles. Not sure what I'm doing wrong. Thank you
Check the following things, you must be missing one or more:
1. Your plugin should export a method. That method should receive an 'inject' function and use it to register your 'testButton' function.
So, in your ~/plugins/testButton.js
export default (context, inject) => {
inject('testButton', () => {
console.log('testButton works!')
})
}
2. You shuold register your plugin correctly in the nuxt.conf.js file
Do it like so:
plugins: [
{ src: '~/plugins/testButton.js' },
],
3. Call it as '$testButton()' (note that Nuxt will have added a dollar sign to your method's name).
Your '$testButton' method will now be available from anywhere in your nuxt app. You don't have to import it o create any computed property.
<b-button #click="$testButton">Click Me</b-button>
<script>
export default {
}
</script>

Set request header in Protractor

Is it possible to set request headers in Protractor?
In the following post (2014), Protractor confirmed that currently they don't have any way to do this (as protractor was not designed to interact with under-the-hood things.
here
Has anyone found out a way how to do this?
Thanks in advance :)
I had the same problem so I implemented a simple proxy to inject headers in the requests. I published it on npm repository. You can find it here https://www.npmjs.com/package/headers-injection-proxy
Very easy to use:
header-injection-proxy -p 3000 -t "https://www.google.com" -h "headers.json"
At that point you just send the requests to the proxy instead of the real server
You can use an external library like request. For me it worked as a charm with Protractor:
https://github.com/request/request#custom-http-headers
EDIT:
Here you have an example of implementation. It uses request-promise
import {browser} from 'protractor';
import {put} from 'request-promise';
import {ADMIN_URL} from '../data/definitions/urls';
export class CreateUser {
public setRoles(username: string, roles: string[]) {
return this.getUserId(username).then((userId) => {
const data = {
url: `${ADMIN_URL}/user/${userId}/role`,
headers: {
Authorization: browser.params.token
},
body: roles,
json: true,
rejectUnauthorized: false
};
return put(data);
});
}
}

share a method of use axios globally standard for nuxtjs?

i want use it for all components and pages and my config present :
~/plugins/axios
import axios from 'axios'
export default axios.create({
baseURL: 'http://127.0.0.1:3001/'
})
but with this way , i must import axios from '~/plugins/axios' in components and pages
i want use something choise for like this :
this.$axios.post('url',data).then(res=>{
// do something in here
}).catch({
// do something in here
})
and no need import more axios
I recommend you to use the official "Axios Module" for Nuxt.js: https://github.com/nuxt-community/axios-module
npm install #nuxtjs/axios
First, you can set your baseURL in the nuxt.config.js or in an env variable (see https://axios.nuxtjs.org/options):
modules: [
'#nuxtjs/axios'
],
axios: {
baseURL: 'http://127.0.0.1:3001/' // or, Environment variable API_URL_BROWSER can be used to override browserBaseURL.
}
Then in <page>.vue, no more import, axios is injected in the app var (see https://axios.nuxtjs.org/usage):
<script>
export default {
asyncData ({ app }) {
app.$axios.$get(`/api/users`).then(
// do something in here
);
//...
}
}
</script>
Finally, you can handle errors globally with a custom plugin (see https://axios.nuxtjs.org/extend)
$axios.onError(error => {
// do something in here
})

Using Grunt to Mock Endpoints

I'm using Yeoman, Grunt, and Bower, to construct a platform for building a frontend independently of a a backend. The idea would be that all of my (AngularJS) controller, services, factories, etc live in this project, and get injected afterwards into my serverside codebase based off the result of grunt build.
My question is:
How can I mock endpoints so that the Grunt server responds to the same endpoints as my (Rails) App will?
At the moment I am using:
angular.module('myApp', ['ngResource'])
.run(['$rootScope', function ($rootScope) {
$rootScope.testState = 'test';
}]);
And then in each of my individual services:
mockJSON = {'foo': 'myMockJSON'}
And on every method:
if($rootScope.testState == 'test'){
return mockJSON;
}
else {
real service logic with $q/$http goes here
}
Then after grunt build, testState = 'test' gets removed.
This is clearly a relatively janky architecture. How can I avoid it? How can I have Grunt respond to the same endpoints as my app (some of which have dynamic params) apply some logic (if necessary), and serve out a json file (possibly dependent on path params)?
I've fixed this issue by using express to write a server that responds with static json.
First I created a directory in my project called 'api'. Within that directory I have the following files:
package.json:
{
"name": "mockAPI",
"version": "0.0.0",
"dependencies": {
"express": "~3.3.4"
}
}
Then I run npm install in this directory.
index.js:
module.exports = require('./lib/server');
lib/server.js:
express = require('express');
var app = express();
app.get('/my/endpoint', function(req, res){
res.json({'foo': 'myMockJSON'});
});
module.exports = app
and finally in my global Gruntfile.js:
connect: {
options: {
port: 9000,
hostname: 'localhost',
},
livereload: {
options: {
middleware: function (connect, options) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app),
require('./api')
];
}
}
},
Then the services make the requests, and the express server serves the correct JSON.
After grunt build, the express server is simply replaced by a rails server.
As of grunt-contrib-connect v.0.7.0 you can also just add your custom middleware to the existing middleware stack without having to manually rebuild the existing middleware stack.
livereload: {
options: {
open: true,
base: [
'.tmp',
'<%= config.app %>'
],
middleware: function(connect, options, middlewares) {
// inject a custom middleware into the array of default middlewares
middlewares.push(function(req, res, next) {
if (req.url !== '/my/endpoint') {
return next();
}
res.writeHead(200, {'Content-Type': 'application/json' });
res.end("{'foo': 'myMockJSON'}");
});
return middlewares;
}
}
},
See https://github.com/gruntjs/grunt-contrib-connect#middleware for the official documentation.
Alternatively you can use the grunt-connect-proxy to proxy everything that is missing in your test server to an actual backend.
It's quite easy to install, just one thing to remember when adding proxy to your livereload connect middleware is to add it last, like this:
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app),
proxySnippet
];
}
grunt-connect-prism is similar to the Ruby project VCR. It provides an easy way for front end developers to record HTTP responses returned by their API (or some other remote source) and replay them later. It's basically an HTTP cache, but for developers working on a Single Page Application (SPA). You can also generate stubs for API calls that don't exist, and populate them the way you want.
It's useful for mocking complex & high latency API calls during development. It's also useful when writing e2e tests for your SPA only, removing the server from the equation. This results in much faster execution of your e2e test suite.
Prism works by adding a custom connect middleware to the connect server provided by the grunt-contrib-connect plugin. While in 'record' mode it will generate a file per response on the filesystem with content like the following:
{
"requestUrl": "/api/ponies",
"contentType": "application/json",
"statusCode": 200,
"data": {
"text": "my little ponies"
}
}
DISCLAIMER: I'm the author of this project.
You can use Apache proxy and connect your REST server with gruntjs.
Apache would do this:
proxy / -> gruntjs
proxy /service -> REST server
you would use your application hitting Apache and angular.js application would think that is talking with itself so no cross domain problem.
Here is a great tutorial on how to set this up:
http://alfrescoblog.com/2014/06/14/angular-js-activiti-webapp-with-activiti-rest/
Just my alternative way that based on Abraham P's answer. It does not need to install express within 'api' folder. I can separate the mock services for certain files. For example, my 'api' folder contains 3 files:
api\
index.js // assign all the "modules" and then simply require that.
user.js // all mocking for user
product.js // all mocking for product
file user.js
var user = function(req, res, next) {
if (req.method === 'POST' && req.url.indexOf('/user') === 0) {
res.end(
JSON.stringify({
'id' : '5463c277-87c4-4f1d-8f95-7d895304de12',
'role' : 'admin'
})
);
}
else {
next();
}
}
module.exports = user;
file product.js
var product = function(req, res, next) {
if (req.method === 'POST' && req.url.indexOf('/product') === 0) {
res.end(
JSON.stringify({
'id' : '5463c277-87c4-4f1d-8f95-7d895304de12',
'name' : 'test',
'category': 'test'
})
);
}
else {
next();
}
}
module.exports = product;
index.js just assigns all the "modules" and we simply require that.
module.exports = {
product: require('./product.js'),
user: require('./user.js')
};
My Gruntfile.js file
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app),
require('./api').user,
require('./api').product,
];
}
}
}