how can I config proxy with axios - proxy

I'm working with nuxt.
as the following you see I set config for axios and proxy in the nuxt.config.js but it dose not work and return http://localhost:3000/laravel/register 404 (Not Found)
but I need http://localhost:8000/register.
what is the problem?
nuxt.config.js
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next',
'#nuxtjs/proxy',
],
axios: {
proxy:true,
// baseURL: 'http://localhost:8000',
},
proxy: {
'/laravel': {
target: 'http://localhost:8000',
pathRewrite: { '^/laravel': '/' }
}
},
example use axios
Register() {
try {
const response = this.$axios.$post('/laravel/register', {
data: this.form,
})
console.log(response)
} catch (error) {
console.log(error)
}
},

Related

#sidebase/nuxt-auth refresh token issue with laravel passport

I'm using nuxt 3 with #sidebase/nuxt-auth for my PKCE OAUTH2 authentication flow with my Laravel API which uses Laravel passport. I am done with the implementation of the authentication flow from the Laravel side, and done with the nuxt side, getting the token and saving it.
Then I have created a custom interceptor with ofetch, in order to send the access_token that I fetch from the session at every request.
but when the access token is expired, it is not getting refreshed automatically.
am i missing some configuration? or refresh token is a custom logic i have to write?
I've tried the JWT callback in the #sidebase/nuxt-auth but it didn't work.
This is my current auth configuration:
import {NuxtAuthHandler} from '#auth'
import useCustomFetch from "~/composables/useCustomFetch";
export default NuxtAuthHandler({
providers: [
{
id: 'passport',
name: 'Passport',
type: 'oauth',
version: '2.0',
authorization: {
url: "https://example.com/oauth/authorize",
params: {
scope: '',
prompt: 'front',
},
},
clientSecret: 'awd',
clientId: "96695f40-1578-4b7c-974b-181e0344dcac",
token: 'https://example.com/api/v1/oauth/token',
userinfo: 'https://example.com/api/v1/user',
checks: ['pkce'],
profile(profile: { success: { user: any } }) {
const data = profile.success.user
return {
id: data.id,
name: data.first_name + " " + data.last_name,
email: data.email,
};
},
}
],
cookies: {
},
callbacks: {
async jwt({token, account, user}) {
if (account && user) {
return {
access_token: account.access_token,
refresh_token: account.refresh_token,
accessTokenExpires: account.expires_at,
user
}
}
// #ts-ignore
if (Date.now() < token.accessTokenExpires * 1000) {
return token
}
return await refreshAccessToken(token);
},
async session({session, token}) {
// #ts-ignore
session.user = token.user
// #ts-ignore
session.access_token = token.access_token
// #ts-ignore
session.error = token.error
return session
},
},
events: {
async signOut() {
try {
await useCustomFetch('/oauth/tokens/revoke', {
method: 'POST'
})
} catch (e) {
console.log(e);
}
},
}
})
async function refreshAccessToken(token: any) {
try {
const url = "https://example.com/api/v1/oauth/token";
// #ts-ignore
const refreshedToken: AuthResponse = await $fetch(url, {
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: {
grant_type: 'refresh_token',
refresh_token: token.refresh_token,
client_id: "96695f40-1578-4b7c-974b-181e0344dcac"
}
});
token.access_token = refreshedToken.access_token;
token.accessTokenExpires = Date.now() + refreshedToken.expires_at * 1000;
token.refresh_token = refreshedToken.refresh_token;
return {
...token
}
} catch (error) {
console.log(error)
return {
...token,
error: "RefreshAccessTokenError",
}
}
}
interface AuthResponse {
access_token: string,
refresh_token: string,
token_type: string,
expires_at: number,
}

How to enable cors for apollo-server-lambda

Ok so I see a lot of answers for how to enable cors for apollo-express, but I haven't found one really for apollo-server-lambda.
This is the error that I'm getting from chrome:
Access to XMLHttpRequest at 'https://5j3gae3086.execute-api.us-east-2.amazonaws.com/alpha/'
from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: The 'Access-Control-Allow-Origin' header
has a value 'https://example.com' that is not equal to the supplied origin.
I do not know how to change the value "https://example.com." Here is my code of how I'm trying to create the server:
const { ApolloServer } = require('apollo-server-lambda')
const typeDefs = require('./schema')
const resolvers = require ('./resolvers')
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
playground: {
endpoint: "/alpha/graphql",
},
});
exports.graphqlHandler = server.createHandler({
cors: {
// origin: true,
origin: "http://localhost:4200", // <-- This is not changing the header value. Do I need to do it from the frontend?
credentials: true,
},
});
What else do I need to do here?
Edit
I'm not sure if this is relevant, but here is my graphql.module.ts file. This is how I'm setting grahql in the frontend:
import { NgModule } from '#angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import { ApolloClientOptions, InMemoryCache } from '#apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
const uri = 'https://5j3gae3086.execute-api.us-east-2.amazonaws.com/alpha/'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
return {
link: httpLink.create({ uri,
// these comments are things that I tried with no luck :(
// fetchOptions: {
// mode: 'no-cors',
// },
// headers: {
// 'Access-Control-Allow-Origin': 'http://localhost:4200',
// 'Access-Control-Allow-Methods': 'POST',
// 'Access-Control-Allow-Headers': 'application/json'
// "Access-Control-Allow-Credentials" : true
// "X-CSRFToken": Cookies.get('csrftoken')
// },
}),
cache: new InMemoryCache(),
};
}
#NgModule({
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule { }
Also in case anyone is curious, I'm using AWS Api Gateway to use the lambda, but I believe I have the configuration for cors added correctly on that.
I'm at a loss with this. What do I need to change?
Following the CORS setup instructions here I can successfully use apollo-angular to return results for a simple query. No special headers etc. were needed.
https://www.apollographql.com/docs/apollo-server/deployment/lambda/
// serverless.yml
events:
- http:
path: graphql
method: post
cors: true
- http:
path: graphql
method: get
cors: true
// graphql.js
exports.graphqlHandler = server.createHandler({
cors: {
origin: '*',
credentials: true,
},
});
// graphql.module.ts
import {NgModule} from '#angular/core';
import {APOLLO_OPTIONS} from 'apollo-angular';
import {ApolloClientOptions, InMemoryCache} from '#apollo/client/core';
import {HttpLink} from 'apollo-angular/http';
const uri = 'https://xxx/dev/graphql';
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
return {
link: httpLink.create({uri}),
cache: new InMemoryCache(),
};
}
#NgModule({
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {}
// In Angular 10
this.apollo
.watchQuery({
query: gql`
{
users {
email
}
}
`,
})
.valueChanges.subscribe(result => {
console.log(result.data);
});
Unlike an initial question, graphql.js is replaced to typescript as following.
// graphql.ts
exports.graphqlHandler = server.createHandler({
expressGetMiddlewareOptions: {
cors: {
origin: '*',
credentials: true,
},
},
});

Nuxt dynamic route population using graphQL

In nuxtconfig.js you can use
generate: { routes() {} }
to return all the dynamic routes for your app.
All the examples use axios ie:
import axios from 'axios'
export default {
generate: {
routes: function () {
return axios.get('https://my-api/users')
.then((res) => {
return res.data.map((user) => {
return {
route: '/users/' + user.id,
payload: user
}
})
})
}
}
}
How can i do this with graphQL / apollo?
I have tried this and some other combinations...
let v
apollo: {
posts: {
query: gql`
query posts {
posts {
title
}
}
`,
result({ data, loading, networkStatus }) {
v = data
}
}
},
generate: {
subFolders: true,
routes: function() {
return {
route: '/posts/' + v.title,
payload: v
}
}
},
The error is that i dont think apollo is able to be used in nuxtconfig?
This also doesnt work
generate: {
routes: function() {
apollo: {
posts: {
query:`query posts {
posts {
title
}
}
`,
result({ data, loading, networkStatus }) {
return {
route: '/posts/' + data.title,
payload: data
}
}
}
},
}
},

Unable to fetch data from API (Resource blocked by client) in Vuex

I'm trying to fetch some data from my API using vuex + axios, but the action give me a "Network Error" (ERR_BLOCKED_BY_CLIENT).
when i was using json-server it works fine, but it doesn't work with my API even with 'Allow-Access-Control-Origin': '*'
actions
const actions = {
async fetchSearch({ commit, state }) {
let res
try {
res = await axios(`http://localhost:8000/api/advertisements/search?column=title&per_page=${state.params.per_page}&search_input=${state.params.query.toLowerCase()}&page=${state.params.page}`, {
method: 'GET',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
}
})
} catch(err) {
console.log(err)
}
commit('clearProducts')
commit('setProducts', res.data)
},
setGlobalParams({ commit }, obj) {
commit('clearParams')
commit('setParams', obj)
}
}
component
<script>
/* Vuex import */
import { mapActions } from 'vuex'
export default {
name: 'base-search-component',
data() {
return {
query_obj: {
page: 1,
per_page: 8,
query: ''
}
}
},
methods: {
...mapActions([
'fetchSearch',
'setGlobalParams'
]),
fetchData() {
if (this.query_obj.query === '') {
return
} else {
this.setGlobalParams(this.query_obj)
this.fetchSearch()
this.$router.push({ name: 'search', params: { query_obj: this.query_obj } })
}
}
}
}
</script>
Assuming your cors issue was properly resolved the reason you cannot access the data is that it is being set before the axios promise is being resolved.
Change:
async fetchSearch({ commit, state }) {
let res
try {
res = await axios(`http://localhost:8000/api/advertisements/search?column=title&per_page=${state.params.per_page}&search_input=${state.params.query.toLowerCase()}&page=${state.params.page}`, {
method: 'GET',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
}
})
} catch(err) {
console.log(err)
}
commit('clearProducts')
commit('setProducts', res.data)
}
to:
async fetchSearch({ commit, state }) {
await axios(`http://localhost:8000/api/advertisements/search?column=title&per_page=${state.params.per_page}&search_input=${state.params.query.toLowerCase()}&page=${state.params.page}`, {
method: 'GET',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
commit('clearProducts')
commit('setProducts', response.data)
}).catch(err) {
console.log(err)
}
}
Further you should use mapState. Assuming setProducts is setting a state object like products this would look like:
<script>
/* Vuex import */
import { mapState, mapActions } from 'vuex'
export default {
name: 'base-search-component',
data() {
return {
query_obj: {
page: 1,
per_page: 8,
query: ''
}
}
},
computed: {
mapState([
'products'
])
},
methods: {
...mapActions([
'fetchSearch',
'setGlobalParams'
]),
fetchData() {
if (this.query_obj.query === '') {
return
} else {
this.setGlobalParams(this.query_obj)
this.fetchSearch()
this.$router.push({ name: 'search', params: { query_obj: this.query_obj } })
}
}
}
}
</script>
Now you can refrence this.products in JS or products in your template.

Using socket.io with aurelia

I am trying to use socket.io in the framework aurelia. But when I start my server I get
error /Users/pierrehedkvist/TDDD272017/picasso/node_modules/socket.io-client/dist/socket.io.min.js
I am adding socket.io to my aurelia.json file like this:
"dependencies": [
....
{
"name": "socket.io-client",
"path": "../node_modules/socket.io-client/dist/socket.io.min"
}
]
And I use it like this (app.js). I try to import socket.io-client and test if I can write to the server.
import {inject} from 'aurelia-framework';
import {ApplicationState} from './application-state';
import io from 'socket.io-client';
var socket = io.connect( 'http://localhost:3000' );
io.emit('chat message', "TESTING");
#inject(ApplicationState)
export class App {
constructor (appState) {
this.appState = appState;
console.log(this.appState);
//this.appState.test = "Billy";
this.players = "";
}
/*activate() {
socket.on('chat message', function(msg){
io.emit('chat message', "TESTING");
console.log('message: ' + msg);
});
}*/
configureRouter(config, router) {
config.title = 'Piccasso or Not';
config.map([
{ route: '', moduleId: 'home', nav:true, name: "Home", title: 'Home'},
{ route: 'game', name: 'game',
moduleId: 'control/game', nav: true, title:'Create a game' },
{ route: 'draw', name: 'draw',
moduleId: 'control/draw', nav: true, title:'Draw something' },
{ route: 'theme', name: 'theme',
moduleId: 'theme', nav: true, title:'Theme' },
{ route: 'next-player', name: 'next-player',
moduleId: 'control/next-player', nav: true, title:'Next player' },
{ route: 'guess', name: 'guess',
moduleId: 'control/guess', nav:true, title: 'Guess'}
]);
this.router = router;
}
activate() {
this.message = 'Hellow world';
}
joinGame() {
console.log("Join lobby " + this.lobbyID)
}
createGame() {
console.log("createGame")
}
}
EDIT:
So I found out my path was incorrect, it now is this.
"name": "socket.io-client",
"path": "../node_modules/socket.io-client/socket.io.min"
Then in app.js I put:
import io from 'socket.io-client';
var socket = io.connect( 'http://localhost:3000' );
//io.emit('chat message', "TESTING");
and made a function called test() which is called from a button which successfully sends a message to my server.
test() {
socket.emit('chat message', "testing");
}

Resources