Got this error while doing some react server side rendering with redux
Stack trace
TypeError: Cannot read property 'slice' of null
at dispatchHttpRequest (E:\Projects\real-estate\node_modules\axios\lib\adapters\http.js:84:37)
at httpAdapter (E:\Projects\real-estate\node_modules\axios\lib\adapters\http.js:19:10)
at dispatchRequest (E:\Projects\real-estate\node_modules\axios\lib\core\dispatchRequest.js:52:10)
at process._tickCallback (internal/process/next_tick.js:103:7)
Action
import axios from 'axios';
export const FETCH_USER = 'FETCH_USER';
export const FETCH_POSTS = 'FETCH_POSTS';
const GET_POSTS_URI = '/api/posts';
export const fetchPosts = () => {
let posts = axios.get(GET_POSTS_URI).catch(err => console.log(err));
return {
type: FETCH_POSTS,
payload: posts
}
}
API
app.get('/api/posts', function(req, res, next) {
Post.model.find()
.exec()
.then(function(posts) {
res.send(posts);
}, function(err) {
return next(err);
});
})
I still got the JSON response in the network tab in dev tool, but I could not retrieve the JSON response in the reducers. I also didn't get this error when I used OpenWeatherAPI
You are missing redux-thunk because you need it in order to do side-effect(like api call). Check out this: redux-thunk and redux async actions.
Related
I am new to JS and trying learn node - supertest. I have came across this error. Kindly guide me.
import { describe } from "mocha";
import supertest from "supertest";
import { expect } from "chai";
const request = supertest('https://gorest.co.in/public/v2/');
const api_token = '45faa1e4b06b3cc1d5ecfbe639235376838cf638c85f88cb9bcc04e954bbf77f';
describe('GET /user' , () =>{
it('fetching user details', (done) =>{
request.get(`users?access-token=${api_token}`).end((err,res) =>{
console.log(err);
console.log(res.body);
done();
})
})
})
Console Error Image for the reference:
I'm having issues with creating a class function with optional parameters. I'm plagued with the following error and since I'm a new comer to typescript I'm not really sure as to what I have to change in my code to fix it. This code works perfectly fine in an earlier project written in JS only.
It specifically highlights the getRequestOptions, when I go check it in base-service.ts in the browser error.
08:32:12.755 client.ts:22 [vite] connecting...
08:32:13.067 client.ts:52 [vite] connected.
08:32:17.043 locales-service.ts:7 getting locales
08:32:17.048 base-service.ts:19 get /Api/GetLocales/ undefined undefined undefined
08:32:17.288 base-service.ts:21 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getRequestOptions')
at request (base-service.ts:21)
at getLocales (locales-service.ts:9)
at setup (locale-selector.vue:22)
at callWithErrorHandling (runtime-core.esm-bundler.js:6737)
at setupStatefulComponent (runtime-core.esm-bundler.js:6346)
at setupComponent (runtime-core.esm-bundler.js:6302)
at mountComponent (runtime-core.esm-bundler.js:4224)
at processComponent (runtime-core.esm-bundler.js:4199)
at patch (runtime-core.esm-bundler.js:3791)
at mountChildren (runtime-core.esm-bundler.js:3987)
And my code
base-service.ts
import axios from '#/plugins/axios'
export default class BaseService {
getRequestOptions(url:any, method:any, data?:any, params?:any , customHeaders?:any) {
const headers = {
...customHeaders
}
return {
url:url,
method:method,
data: data,
params: params,
headers: headers,
}
}
async request(method:any, url:any, data?:any, params?:any, headers?:any) {
console.log(method,url,data,params,headers)
const options = this.getRequestOptions(method, url, data, params, headers)
try {
console.log(options)
const response = await axios(options)
console.log("Getting response from api")
console.log(response)
if (response.status === 200) {
return response.data
}
} catch (error) {
console.log(error)
}
}
}
locales-service.ts
import BaseService from '../base-service'
//?Import models in the future
//import { } from '#/common/models'
class LocaleServ extends BaseService {
async getLocales() {
console.log("getting locales")
let result = await super.request(
'get',
'/Api/GetLocales/'
)
console.log(result)
return result
}
}
export const LocaleService = new LocaleServ()
Any help would be greatly appreciated
Edit:
<script lang="ts">
import { ref } from 'vue'
import { defineComponent } from 'vue'
import CountryFlag from 'vue-country-flag-next'
import { LocaleService } from '#/services'
export default defineComponent({
name: 'LocaleSelector',
components: {
CountryFlag
},
setup () {
const { getLocales } = LocaleService
const data = getLocales()
return {
data:data
}
}
})
</script>
And then in the component I call it with {{data}}
The issue lied in the way I called the destructured getLocales() method from LocaleService in locale-service.vue
I noticed that this was undefined after attaching a debugger. According to this article, destructuring it caused it to lose it's context. Therefore when I called getLocales() in base-service.ts, this was undefined.
Simple work around to fix the, caused due to inexperience, problem was to turn.
const { getLocales } = LocaleService
const data = getLocales()
into
const data = LocaleService.getLocales()
I am trying to test a function with Axios get request. when I get a response I'm calling another function to filter the JSON document.
// sample.js
import axios from "axios";
public async getFruitData{
const response = await axios.get("https://api.url.com/search/fruit", {
params: {
client_id: process.env.REACT_APP_UNSPLASH_TOKEN,
query: term
}
});
return this.filtersResponse(response.data.results); //<---throwing error
};
filterResponse(detailsResponse) {
const excludeFruit = ['apple'];
return detailsResponse.filter(record => !excludeFruit.includes(record.fruit_type));
}
here my jest test
import axios from 'axios';
import Fruit from '../app/fruit';
jest.mock('axios');
test('it filter jsont fruit ', async () => {
mockedAxios.get.mockImplementationOnce(() => Promise.resolve({ data: 'test' }));
const result = await getFruitData();
expect(result).toBe({"data": "test"});
expect(filterResponse(record)).toBeDefined()
});
when I run the test it gave me the following error --> TypeError: Cannot read property 'status' of undefined
How can I test this scenario
I'm new in Jest and I'm trying to make test to my async action creators. The problem is that I only have seen examples of tests where there is a method for the action creator and other separate method for the dispatch. My actions creators have the dispatch as an async callback function, but I can't figure out how to make the test.
My Action Reducer looks like this:
export const postConnection = (connectionUrl, username, password) => {
return async (dispatch) => {
const response = await requireAuthActions.post('/db/conexion', JSON.stringify({ connectionUrl, username, password }));
dispatch({ type: POST_CONNECTION, payload: response.data });
history.push('/conexiones');
}
}
And I have trying to do the test script but when I run it it throws me an error. The script looks like this:
describe('Pruebas de Conexiones', () => {
describe('Action Creators', () => {
it("Crear conexión", async () => {
const dispatch = jest.fn();
const {data} = await postConnection('www.google.com', 'root', 'password')(dispatch);
dispatch({});
});
});
});
And when I try to run the test script it throws me the next error:
Request failed with status code 401
at createError (node_modules/axios/lib/core/createError.js:16:15)
at settle (node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:237:11)
Is there a way of test actions creators like the mine?
EDIT
Now I have a mocks file with a mock for axios that looks like this:
const mockAxios = jest.genMockFromModule('axios');
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios
But now my problems is that I don't know how to implement this in the test file. For now I have something like this:
import thunk from 'redux-thunk';
import mockAxios from 'axios';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('Test de conexiones', () =>{
describe('Action Creators', () =>{
it('Agregar conexión', async () =>{
const store = mockStore({});
const mockData = {data:123};
mockAxios.get.mockImplementationOnce(()=>Promise.resolve({data: mockData}));
const expectedActions = [
{type: POST_CONNECTION, data: mockData}
]
const dispatch = jest.fn();
const response = await postConnection('www.google.com','root','password')(dispatch);
});
});
});
And it throws me the next error:
TypeError: Cannot read property 'data' of undefined
12 | return async (dispatch) => {
13 | const response = await requireAuthActions.post('/db/conexion', JSON.stringify({ connectionUrl, username, password }));
> 14 | dispatch({ type: POST_CONNECTION, payload: response.data });
| ^
15 | history.push('/conexiones');
16 | }
17 | }
I see 2 approaches possible: using real store or redux-mock-store
Steps are similar:
Set up store.
mock external API like http call or at least requireAuthActions module with some response(successful or failed)(check jest's docs on mocking)
make a pause to await(await Promise.resolve();, flush-promises or setTimeout(..., 0)) all async things like Promise.resolve() you mocked in #2.
if you use real store - then check against store(with selectors if you use this level of abstraction) if it contains data you would expect to see based on response you mocked in #2
if it's redux-mock-store you cannot verify data in state(so reducers should be tested separately) so just validate list of actions generated - if they meet expectations based on response mocked in #2 or not.
When trying to use axis to query an external Weather API, I get this error
ReferenceError: axios is not defined
at getTropicalCyclones (vm.js:16:9)
Here is my action for getTropicalCyclones {}
(of course I have to hide my client ID and secret)
const getTropicalCyclones = async () => {
const BASE_WEATHER_API = `https://api.aerisapi.com/tropicalcyclones/`
const CLIENT_ID_SECRET = `SECRET`
const BASIN = `currentbasin=wp`
const PLACE = `p=25,115,5,135` // rough coords for PH area of responsibility
const ACTION = `within` // within, closest, search, affects or ''
try {
let text = ''
let response = {}
await axios.get(
`${BASE_WEATHER_API}${ACTION}?${CLIENT_ID_SECRET}&${BASIN}&${PLACE}`
)
.then((resp) => {]
response = resp
text = 'Success retrieving weather!'
})
.catch((error) => {
console.log('!! error', error)
})
const payload = await bp.cms.renderElement(
'builtin_text',
{
text,
},
event.channel
)
await bp.events.replyToEvent(event, payload)
} catch (e) {
// Failed to fetch, this is where ReferenceError: axios is not defined comes from
console.log('!! Error while trying to fetch weather info', e)
const payload = await bp.cms.renderElement(
'builtin_text',
{
text: 'Error while trying to fetch weather info.',
},
event.channel
)
await bp.events.replyToEvent(event, payload)
}
}
return getTropicalCyclones()
So my question is, how do I import axios? I've tried
const axios = require('axios')
or
import axios from 'axios';
but this causes a different error:
Error processing "getTropicalCyclones {}"
Err: An error occurred while executing the action "getTropicalCyclones"
Looking at the package.json on GitHub, it looks like axios is already installed
https://github.com/botpress/botpress/blob/master/package.json
However, I cannot locate this package.json on my bot directory...
Secondly, based on an old version doc it looks like this example code just used axios straight
https://botpress.io/docs/10.31/recipes/apis/
How do I use axios on Botpress?
Any leads would be appreciated
Botpress: v11.0.0
Simply use ES6 import.
include this line at the top of your code.
import axios from 'axios';
Note: I'm expecting that the axios is already installed