callApi with Login to access .json File - vuejs - javascript

i want to access a .json file via link.
when i type in the link to my json file in my browser, it asks for credentials (username + password) which i know.
i want to write the credentials in the code, so i dont have to log in manually anymore,
OR
get a message to log in with my credentials when the website is trying to fetch the data from the json file.
of course if there are other possibilities to access the json other than a callApi method you're welcome. :)
present code without authentication and with a local file:
<script>
import jsonData from '../../static/json/test.json'
export default {
name: 'dash',
data() {
return {
data: ''
}
},
mounted() {
this.fetchData()
},
methods: {
fetchData() {
this.callApi()
.then((responseData) => {
this.data = responseData;
})
},
callApi() {
return Promise.resolve(jsonData)
}
}
}
</script>

In case you are using basic authentication you can add your username and password in the beginning of the url separated by a colon. So an example url would be https://username:password#www.example.com/
Note that this is not a good practice and should not be used in production.

Related

How to restrict user to display login page if already logged in using Reactjs

I am working on Reactjs and using nextjs framework, I am working on "Login Logout" module and i just want that if user already logged in ( email set in cookie) then he should redirect to "dashboard" page,How can i do this ? I tried with following code but not working for me, giving me error ",Here is my current code
cookies returned from getServerSideProps Reason: undefined cannot be serialized as JSON
export async function getServerSideProps(context: { req: { headers: { cookies: any; }; }; }) {
const cookies = context.req.headers.cookies;
if (cookies && cookies.email) {
// email is present in cookies, so redirect to /dashboard
return {
redirect: {
destination: "/dashboard",
statusCode: 302, // temporary redirect
},
props: {},
};
}
return {
props: {
cookies,
},
};
}
When returning props.cookies from getServerSideProps, you are potentially returning the cookies as undefined. Use '' as the default value if missing.
You can do this:
return {
props: {
cookies: cookies || '',
},
};
You need to parse the cookies and you can get the cookies on the request you don't need the header
const cookies = JSON.parse(context.req.cookies);
if(cookies.email !== undefined)...

Axios get call in Vue3 not working, although curl and javascript work as expected

I'm trying to make an API call from my Vue3 app. The prepared API has an endpoint like http://localhost:8888/api/dtconfigsearch, where one needs to pass a json payload like { "Modelname": "MyFancyModel"} to get the full dataset with the given modelname. Pure get functions without a payload / a body do work from my Vue3 project to the golang backend, but I'm having problems with passing a payload to the backend.
Test with curl -> ok
$ curl -XGET localhost:8888/api/dtconfigsearch -d '{"Modelname" : "MyFancyModel" }'
{"ID":4,"Modelname":"MyFancyModel","ModelId":"96ee6e80-8d4a-b59a-3524-ced3187ce7144000","OutputTopic":"json/fancyoutput"}
$
This is the expected output.
Test with javascript ok
Source file index.js:
const axios = require('axios');
function makeGetRequest() {
axios.get(
'http://localhost:8888/api/dtconfigsearch',
{
data: { Modelname : "MyFancyModel" },
headers: {
'Content-type' : 'application/json'
}
}
)
.then(resp => {
console.log(resp.data)
})
.catch(err => {
console.log(err)
})
}
makeGetRequest()
Output
$ node index.js
{
ID: 4,
Modelname: 'MyFancyModel',
ModelId: '96ee6e80-8d4a-b59a-3524-ced3187ce7144000',
OutputTopic: 'json/fancyoutput'
}
$
Here, I also get the desired output.
Test within Vue fails :-(
Source in the Vue one file component:
onSelection(event) {
let searchPattern = { Modelname : event.target.value }
console.log(event.target.value)
console.log("searchPattern = " + searchPattern)
axios.get("http://localhost:8888/api/dtconfigsearch",
{
data : { Modelname : "Windshield"},
headers: {
'Content-type' : 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
.then(response => {
console.log(response.data)
})
.catch(err => {
console.log(err)
alert("Model with name " + event.target.value + " not found in database")
})
},
Output in browser:
In the image you can see in the terminal log on the right side that the backend is not receiving the body of the API call. However, in the browser information of the call there is content in the config.data part of the object tree, which is the payload / the body. The only thing that bothers me that it is not a json object, but stringified json, although it was entered as json object. According to the documentation, the parameter name (data) in the call should be correct to hold the body content of the api call.
I've tried different header information, looked if it could be a CORS issue, what it isn't to my opinion, exchanged key data with body, used axios instead of axios.get and adapted parameter, all without success. The version of the axios library is 0.27, identical for Vue and vanilla javascript. After checking successfully in javascript, I was sure that it would work the same way in Vue, but it didn't.
Now I'm lost and have no further ideas how to make it work. Maybe someone of you had similar issues and could give me a hint? I'd be very grateful for some tipps!!

Where to store Laravel Passport "client_secret" in VueJS

I am a bit new to VueJS and I am using Laravel as API only and VueJS as a separate project.
In my App.vue, I have following setup:
http://api.com is my virtual host!
<script>
import axios from 'axios';
export default {
data () {
return {
}
},
created() {
const postData = {
grant_type: "password",
client_id: 2,
client_secret: 'MvEyvm3MMr0VJ5BlrJyzoKzsjmrVpAXp9FxJHsau',
username: 'mail#gmail.com',
password: '**********',
scope: ''
}
axios.post('http://api.com/oauth/token', postData)
.then(response => {
const header = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + response.data.access_token,
};
axios.get('http://api.com/api/user', { headers: header })
.then(response => {
console.log(response.data)
})
})
}
}
</script>
But this file is totally visible to front-end which is not good due to security reasons.
What I did, I made a new route in Laravel as Route::post('get_client_creds', MyController#index); and then made a request from axios as:
axios.post('http://api.com/get_client_creds')
.then(response => {
this.client_secret = response.client_secret;
});
And but then I thought anyone can also access the route using Postman or may be through console using axois, so can someone give me some suggestions about where to store these secrets???
Thanks in Advance!
There are two different ways to specify config settings for vue
#1 Vue.js non-cli projects, you can use src/config.js
Create a new file src/config.js and add as following
export const API_CLIENT_ID = '123654';
To use this, try import like:
import { API_CLIENT_ID } from '../config'
// in your code
console.log(API_CLIENT_ID);
#2 For Vue CLi projects follow these steps.
You must use the .env files hold the configuration variables.
It could be structured like
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
Here is how you can specify the variable.
FOO=bar
API_CLIENT_ID=123456
And you can use this as:
console.log(process.env.API_CLIENT_ID)
Please follow the documentation for more details.
https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

How to create custom Registration and Login API using Strapi?

I am using strapi to create APIs.
I want to implement my own Registration API and Login API.
I checked the documentation of strapi but i am not finding any custom API for this.
can any one help me on this?
Same answer, but in more detail:
Strapi creates an Auth controller automatically for you and you can overwrite its behavior.
Copy the function(s) you need (e.g. register) from this file:
node_modules/strapi-plugin-users-permissions/controllers/Auth.js
to:
your_project_root/extensions/users-permissions/controllers/Auth.js
Now you can overwrite the behavior, e.g. pass a custom field inside the registration process {"myCustomField": "hello world"} and log it to the console:
async register(ctx) {
...
...
// log the custom field
console.log(params.myCustomField)
// do something with it, e.g. check whether the value already exists
// in another content type
const itExists = await strapi.query('some-content-type').findOne({
fieldName: params.myCustomField
});
if (!itExists) {
return ctx.badRequest(...)
} else {
console.log('check success')
}
}
Actually, strapi creates an Auth controller to handle these requests. You can just change them to fit in your need.
The path to the controller is:
plugins/users-permissions/controllers/Auth.js
in order to create custom users-permissons apis on server side you have to create
src/extensions/users-permissions/strapi-server.js
and in that file can write or override existing user-permissions plugin apis
here is the example for users/me
const _ = require('lodash');
module.exports = (plugin) => {
const getController = name => {
return strapi.plugins['users-permissions'].controller(name);
};
// Create the new controller
plugin.controllers.user.me = async (ctx) => {
const user = ctx.state.user;
// User has to be logged in to update themselves
if (!user) {
return ctx.unauthorized();
}
console.log('calling about meeeeeeeeeee------')
return;
};
// Add the custom route
plugin.routes['content-api'].routes.unshift({
method: 'GET',
path: '/users/me',
handler: 'user.me',
config: {
prefix: '',
}
});
return plugin;
};

How to send JSON data correctly using Axios to a rails server, to match the required rails params hash correctly?

I am making a GET request to a rails server, and the parameter should look like:
{"where"=>{"producer_id"=>["7"]}
I am making the request from the frontend application which is in Vue, and using Axios for making the request. I am making the request like this:
const data = await this.axios.get('http://localhost:3000/data.json', {
headers: {
'X-User-Token': this.$store.getters.authToken,
'X-User-Username': this.$store.getters.user.username
},
params: {
where: {
producer_id: data.producers
}
}
})
However, in the rails server output it shows that the params were sent like this:
{"where"=>"{\"producer_id\":[\"7\"]}"}
And I don't get the correct data back because of it.
How can I solve this? Why is the second level in params (the where object) being sent as a string?
Turns out that in this case the params have to be serialized https://github.com/axios/axios/issues/738
I used the paramsSerializer function as well to get over this
const data = await this.axios.get('http://localhost:3000/data.json', {
headers: {
'X-User-Token': this.$store.getters.authToken,
'X-User-Username': this.$store.getters.user.username
},
params: {
where: {
producer_id: data.producers
}
},
paramsSerializer: function (params) {
return jQuery.param(params)
}
})
EDIT:
I am now using qs instead of jQuery:
axios.defaults.paramsSerializer = (params) => {
return qs.stringify(params, {arrayFormat: 'brackets'})
}

Categories

Resources