NestJS: Adding cookie-parser causes an error - cookies

When I run this code:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import cookieParser from 'cookie-parser';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(cookieParser());
await app.listen(3000);
}
bootstrap();
I get:
(node:28) UnhandledPromiseRejectionWarning: TypeError: cookie_parser_1.default is not a function
at bootstrap (/usr/src/app/dist/main.js:8:36)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
If I comment out "app.use(cookieParser());" the problem goes away, but I need the cookie parser.

I literally found this as I was about to hit submit.
Modify the above to have
import * as cookieParser from 'cookie-parser';
and it works as expected.

Related

Setting Global Axios Headers in Vue 3

I am trying to use Axios to hit my backend (Django), but I am having some trouble setting my global headers to include the CSRF token in the header.
This is reaching my server:
import axios from "axios";
async function loadCards() {
var instance = axios.create({
xsrfCookieName: window.rootData.csrfToken,
xsrfHeaderName: "X-CSRFTOKEN",
});
return await instance.post(window.rootData.urlpaths.loadCards, {
'state': props.state.label,
'filter': props.filter.label,
'project': window.rootData.project
})
}
However, I want these headers to apply to all of my internal api requests. So I thought I would establish them in a separate file:
axios-site.js
import axios from "axios";
var siteApi = axios.create({
xsrfCookieName: window.rootData.csrfToken,
xsrfHeaderName: "X-CSRFTOKEN",
});
export default {
siteApi
}
Vue Component
import siteApi from "#/axios-site";
setup () {
async function loadCards() {
return await siteApi.post(window.rootData.urlpaths.loadCards, {
'state': props.state.label,
'filter': props.filter.label,
'project': window.rootData.project
})
}
}
Here is the error in console:
Uncaught (in promise) TypeError: _axios_site__WEBPACK_IMPORTED_MODULE_4__.default.post is not a function
at _callee$ (ActionColumn.vue?ba4f:97)
at tryCatch (runtime.js?96cf:63)
at Generator.invoke [as _invoke] (runtime.js?96cf:293)
at Generator.eval [as next] (runtime.js?96cf:118)
at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
at _next (asyncToGenerator.js?1da1:25)
at eval (asyncToGenerator.js?1da1:32)
at new Promise (<anonymous>)
at eval (asyncToGenerator.js?1da1:21)
at _loadCards (ActionColumn.vue?ba4f:80)
It seems something is being lost when I run it through the external file. I'm sure I am missing something obvious, but I can't seem to pinpoint it. I found another accepted answer that follows a similar logic here, but it isn't working in my case. Is it possible that webpack is screwing things up?
You should export the axios instance like :
export default siteApi
then in main.js add it to globalProperties :
import siteApi from "#/axios-site";
...
app.config.globalProperties.siteApi=siteApi
in any child component you'll have access to that property :
import { getCurrentInstance } from 'vue'
const MyComponent = {
setup() {
const internalInstance = getCurrentInstance()
const {siteApi}= internalInstance.appContext.config.globalProperties
async function loadCards() {
return await siteApi.post(window.rootData.urlpaths.loadCards, {
'state': props.state.label,
'filter': props.filter.label,
'project': window.rootData.project
})
}
}
}
in options api like mounted hook :
mounted(){
this.siteApi.post(...)
}

Unit/Jest test with bootstrap vue Fail

I got this error when I try to run a test on bootstrap vue components:
"ReferenceError: BootstrapVue is not defined"
In the .spec.js file I added this:
import TableSummary from "#/components/TableSummary";
import { createLocalVue, mount } from "#vue/test-utils";
const localVue = createLocalVue();
localVue.use(BootstrapVue);
describe('TableSummary', ()=> {
test('if the user is typing, the button becomes enabled', async ()=> {
const wrapper = mount(TableSummary, { localVue });
wrapper.setData({isDisabled: true});
await wrapper.vm.$nextTick;
expect(wrapper.find('input').state.isDisabled).toBe(false);
});
});
I ran the same instructions as a correct answer here on stack overflow but still, it doesn't work for me... I couldn't comment on the answer as I am not level 50, and I had to open a new question.
I think you need to import the BootstrapVue
import BootstrapVue from 'bootstrap-vue'

Mocha Chai vue testing a vue component : this.$notify is not a function

I'm using this component : https://github.com/euvl/vue-notification
Since then, all of my Mocha chai test units are failing .
this.$notify is not a function
This is my login spec :
// Importing The testing library
import { expect } from "chai";
import { mount } from '#vue/test-utils'
// Importing The component I need to test
import Login from "#/components/Login.vue";
// Mounting the component as in real life
const wrapper = mount(Login);
describe("Login test", () => {
it("getAuth() to be a function", () => {
expect(wrapper.vm.getAuth).to.be.a("function");
});
});
I've tried out mount, shallowMount, render with no luck .
Any workaround ?
I'm calling vue-notification in main.js like this :
import Notifications from "vue-notification";
Vue.use(Notifications);
Thank you !
EDIT :
Ive tried to add
const $notify = require('vue-notification')
To my Login.vue component with no luck
EDIT 2 : Tried to call the function like this with no luck :
this.$root.$notify({
group: 'foo',
title: 'Hello ',
text: 'Cool'
});
[Vue warn]: Error in mounted hook: "TypeError: this.$root.$notify is not a function"
*EDIT : ***** Resolved by me ****** *
I was badly importing vue . Please see my working login.spec.js testing file there :
// THE ASSERTION LIBRARY
import { expect } from "chai";
// THE TESTING LIBRARY
import { mount } from "#vue/test-utils";
// THE COMPONENT THAT I WANT TO TEST
import Login from "#/components/Login.vue";
// THE EXTERNAL COMPONENTS LINKED TO MY LOGIN COMPONENT THAT I NEED TO JOIN
import Vue from 'vue';
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
import {
required,
minLength,
between
} from "vuelidate/lib/validators";
import Notifications from "vue-notification";
import velocity from 'velocity-animate'
Vue.use(Notifications, { velocity });
// THE WRAPPER CONTAIN MY LOGIN MOUNTED COMPONENT, JUST LIKE IN THE REAL LIFE
const wrapper = mount(Login)
describe("Login test", () => {
it("getAuth() to be a function", () => {
expect(wrapper.vm.getAuth).to.be.a("function");
});
});

Apollo-client returns "400 (Bad Request) Error" on sending mutation to server

I am currently using the vue-apollo package for Apollo client with VueJs stack with django and graphene-python for my GraphQl API.
I have a simple setup with vue-apollo below:
import Vue from 'vue'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'
import Cookies from 'js-cookie'
const httpLink = new HttpLink({
credentials: 'same-origin',
uri: 'http://localhost:8000/api/',
})
// Create the apollo client
const apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
connectToDevTools: true,
})
export const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
// Install the vue plugin
Vue.use(VueApollo)
I also have CORS setup on my Django settings.py with the django-cors-headers package. All queries and mutations resolve fine when I use graphiQL or the Insomnia API client for chrome, but trying the mutation below from my vue app:
'''
import gql from "graphql-tag";
import CREATE_USER from "#/graphql/NewUser.gql";
export default {
data() {
return {
test: ""
};
},
methods: {
authenticateUser() {
this.$apollo.mutate({
mutation: CREATE_USER,
variables: {
email: "test#example.com",
password: "pa$$word",
username: "testuser"
}
}).then(data => {
console.log(result)
})
}
}
};
NewUser.gql
mutation createUser($email: String!, $password: String!, $username: String!) {
createUser (username: $name, password: $password, email: $email)
user {
id
username
email
password
}
}
returns with the error response below:
POST http://localhost:8000/api/ 400 (Bad Request)
ApolloError.js?d4ec:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400
Regular queries in my vue app, however, work fine resolving the right response, except mutations, so this has me really baffled
400 errors generally mean there's something off with the query itself. In this instance, you've defined (and you're passing in) a variable called $username -- however, your query references it as $name on line 2.
In addition to graphiQL, I would like to add that apollo-link-error package would also had been of great help.
By importing its error handler { onError }, you can obtain great detail through the console about errors produced at network and application(graphql) level :
import { onError } from 'apollo-link-error';
import { ApolloLink } from 'apollo-link';
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
console.log('graphQLErrors', graphQLErrors);
}
if (networkError) {
console.log('networkError', networkError);
}
});
const httpLink = ...
const link = ApolloLink.from([errorLink, httpLink]);
const client = new ApolloClient({
...,
link,
...
});
By adding this configuration where you instantiate your Apollo Client, you would have obtained an error similar to this one:
GraphQLError{message: "Syntax Error: Expected {, found Name "createUser""}
Further information can be found in Apollo Doc - Error handling: https://www.apollographql.com/docs/react/features/error-handling.
Hope it helps in the future.
For me, it was the fact that I was using a field not defined in the GraphQL schema. Always be careful!
For sure the mutation is not formatted correctly if that is exactly what you are sending. You need an opening bracket in the mutation
mutation createUser($email: String!, $password: String!, $username: String!) {
createUser (username: $name, password: $password, email: $email) {
user {
id
username
email
password
}
}
}
With any of these queries when i run into bugs i paste it into either graphiql or graphql playground to identify what the formatting errors is in order to isolate what is wrong.
For people using laravel for backend, this helped me solve the problem
In the laravel project find file config/cors.php and change line 'paths' => ['api/*', 'sanctum/csrf-cookie'], to 'paths' => ['api/*', 'graphql', 'sanctum/csrf-cookie'],
Also in your vue app ensure that you're not using the no-cors mode in apollo config
Regards

ionic 2 TypeError: self.context.doInfinite is not a function

I am trying to load more data from the server and i am getting error in a console
zone.js:260
Uncaught EXCEPTION: Error in build/pages/home/home.html:30:23
ORIGINAL EXCEPTION: TypeError: self.context.doInfinite is not a function
ORIGINAL STACKTRACE:
TypeError: self.context.doInfinite is not a function
at DebugAppView._View_HomePage0._handle_ionInfinite_25_0..
home.ts has the following codes
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
import {JobService} from '../job/job';
import {JobPage} from '../services/JobService';
#Component({
templateUrl: 'build/pages/home/home.html',
providers:[JobService]
})
export class HomePage {
public posts:any = [];
private start:number=0;
constructor(private navCtrl: NavController, public peopleService:PeopleService) {
this.loadPeople();
}
loadPeople() {
return new Promise(resolve => {
this.peopleService.load(this.start)
.then(data => {
for(let kazitz of data) {
this.posts.push(kazitz);
}
resolve(true);
});
});
}
doInfinite(infiniteScroll) {
console.log('doInfinite, start is currently '+this.start);
this.start+=5;
this.loadPeople().then(()=>{
infiniteScroll.complete();
});
}
}
Now, error says doInfinite is not a function while it is a function you see above, i am getting this error while the app tries to load more data.. in home.html normal ionic 2 load more codes i took from ionic framework docs
<ion-infinite-scroll (ionInfinite)="doInfinite($event)">
<ion-infinite-scroll-content
loadingSpinner="bubbles"
loadingText="Loading more...">
</ion-infinite-scroll-content>
</ion-infinite-scroll>
Any help will be appreciated!
I had the same issue, and it only worked when i added this.doInfinite(); to the Constructor() like this:
Constructor(){
this.doInfinite();
}
I cannot guarantee it will work, and I apologise if it doesn't. I am honestly still perplexed by it. Good luck!