MERN Project Deploy to Heroku, axios function fail - mongodb

I tried to deploy my local running MERN stack project to Heroku. The UI is showing fine, but the axios calls continue to fail. Here is how I wrote the axios URL.
axiosConfig.js:
import axios from "axios";
const api = axios.create({
baseURL: process.env.REACT_APP_BASE_URL // or process.env.BASE_URL if not using CRA
});
export default api
Arrival.js:
import api from '../../axiosConfig';
const Arrivals = () => {
const baseURL = api || "http://localhost:5000";
useEffect(() => {
axios.get(baseURL + '/flights/arrivals/' + timeDuration)
.then((response) => {
setData(response.data);
console.log(data)
})
.catch(err => {
console.log(err)
})
}, [timeDuration]);//eslint-disable-line
When I call the api, the network showing it's tring to get from:
https://minions-airport-202.herokuapp.com/function()%7Breturn%20e.apply(t,arguments)%7D/flights/arrivals/28800000
And it is getting 500 Internal Server Error. Any idea why?

Related

Can Bunjs be used as a backend server?

Now we can start a react App with bun as a server
Can we use Bunjs as complete backend server?
For Example, Can bun run this code?
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('hello world')
})
app.listen(3000)
I guess Bun does not YET implement all node.js api's. I tried http and it seems currently missing. And as much I understand it currently has its own built-in HTTP server.
Check the "Getting started" section on -> https://bun.sh/
A sample server:
export default {
port: 3000,
fetch(request) {
return new Response("Welcome to Bun!");
},
};
(This example reminds me of serverless functions.)
As this is the case, it seems you can not rely on Node.js http, or most probably any server framework like express.
At least for now, bun's roadmap (https://github.com/oven-sh/bun/issues/159) shows a line, which I am not sure is talking about node's http server or sth. else about Bun's own server.
Once complete, the next step is integration with the HTTP server and
other Bun APIs
Bun api is really different from nodejs, I created a library called bunrest, a express like api, so new user does not need to learn much about bun.
Here is how to use it
Install the package from npm
npm i bunrest
To create a server
const App = require('bunrest');
const server = new App.BunServer();
After that, you can call it like on express
server.get('/test', (req, res) => {
res.status(200).json({ message: 'succeed' });
});
server.put('/test', (req, res) => {
res.status(200).json({ message: 'succeed' });
});
server.post('/test', (req, res) => {
res.status(200).json({ message: 'succeed' });
});
To start the server
server.listen(3000, () => {
console.log('App is listening on port 3000');
});
Other way is using Hono: https://honojs.dev/
There is a working demo: https://github.com/cachac/bun-api
Import package and set new instance
import { Hono } from 'hono'
const app = new Hono()
Create routes:
Instead of NodeJs res.send(), use c.json({})
app.get('/hello', c => c.json({ message: 'Hello World' }))
export and run api server:
export default {
fetch: app.fetch,
port: 3000
}

How to initialize Mongodb in NextJS startup

As you know NextJS is Jamstack framework and I'm migrating from node/express to it but my problem is how to connect server to database at startup of server as i did in express?
there is now where to put my initalizing code in NextJS? Am I saying correct?
I saw some code to to that but there were typescript codes that im not familiar with them
On the other hand i'm able to do that on serverside functions like getStaticProps or getServerSideProps this is my code
dbinit.js
import mongoose from "mongoose";
export const dbStatus = () => mongoose.connection.readyState;
export default function dbConnect() {
if (dbStatus == 1) return "database is connected";
mongoose.connect(
`mongodb://localhost:${process.env.DBPORT}/${process.env.DBNAME}`
);
}
index.js
export async function getServerSideProps() {
const result = await dbConnect();
console.log(dbStatus());
return {
props: {},
};
}
with this code im able to connect to mongodb but there are some problems and the most important is that mycode isnot cleancode
In NextJS, we can connect MongoDB as middleware. This is very similar to the Express middleware approach as shown below.
// middleware/database.js
import { MongoClient } from 'mongodb';
import nextConnect from 'next-connect';
const client = new MongoClient('{YOUR-MONGODB-CONNECTION-STRING}', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function database(req, res, next) {
if (!client.isConnected()) await client.connect();
req.dbClient = client;
req.db = client.db('MCT');
return next();
}
const middleware = nextConnect();
middleware.use(database);
export default middleware;
For more details, you can refer to this official how-to doc for step-by-step guidance. Here is the example repository used.

Nuxt vuex - moving store from Vue

I have been fiddling with moving a tutorial I did in Vue to Nuxt. I have been able to get everything working, however I feel I'm not doing it the "proper way". I have added the Nuxt axios module, but wasnt able to get it working, so I ended up just using the usual axios npm module. Here is my store:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex)
Vue.use(VueAxios, axios)
export const state = () => ({
events: []
})
export const mutations = {
setEvents: (state, events) => {
state.events = events
}
}
export const actions = {
loadEvents: async context => {
let uri = 'http://localhost:4000/events';
const response = await axios.get(uri)
context.commit('setEvents', response.data)
}
}
I would like to know how to re-write this store using the #nuxtjs/axios module. I also didnt think I'd need to import vuex here, but if I dont, my app doesn't work.
Thanks for any help!
Using the #nuxtjs/axios module, you can configure axios inside your nuxt.config.js:
// nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
],
axios: {
// proxy: true
}
}
You can use it inside your store (or components) with this.$axios
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}

API works with Postman, but not Axios

I am trying to get data from a 3rd-party API, but cannot get any data back from it in my program. However, I can get it to work via Postman.
params in Postman:
JSON from Postman:
JSON from console:
the code in question:
const consola = require('consola');
const express = require('express');
const axios = require('axios');
const app = express();
// GET - /api/title
app.get('/', (req, res) => {
const title = 'and then there were none'; // this is just until data is coming from user input
const replaceSpaces = (str) => str.split(' ').join('+');
axios
.get('https://tastedive.com/api/similar', {
params: {
q: replaceSpaces(title),
type: 'books',
info: 1,
limit: 7,
k: process.env.TASTE_DIVE_KEY,
},
})
.then(({ data }) => {
consola.ready({
message: `data from axios server ${JSON.stringify(data)}`,
badge: true,
});
res.json(data);
})
.catch((error) => {
res.status(400).json(error);
consola.error({
message: `error from axios server ${error}`,
badge: true,
});
});
});
Does anybody know what could be causing this discrepancy? I have the same params in both my code and in Postman, but I'm not getting the full data back in my app that I am in Postman.

Write test axios-mock-adapter with axios.create()

I want to test my http service but get error.
So, my test file
api.js
import axios from 'axios';
export const api = axios.create();
fetchUsers.js
import api from './api';
export const fetchUsers = (params) api.get('/api/users', { params })
.then(({data}) => data)
fetchUsers.spec.js
import MockAdapter from 'axios-mock-adapter'
import api from './api';
const mock = new MockAdapter(api);
describe('fetchUsers', () => {
it('should send request', (done) => {
const data = { data: ['user'] };
mock.onGet('/api/users').reply(200, data);
fetchUsers().then((response) => {
expect(response).toEqual(data.data);
done();
});
});
});
But I get error here
Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1158:14)
If I replace in api.js axios.create() with axios its' working. But how to test with created axios instance? I'll need to ass there parameters when create it.
Anyone can help with that?
Hi I had the same issue and had to answer myself here https://stackoverflow.com/a/51414152/73323
Here is the gist:
First off, you don't need the axios-mock-adapter library.
Create a mock for axios in src/__mocks__:
// src/__mocks__/axios.ts
const mockAxios = jest.genMockFromModule('axios')
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios
Then in your test file, the gist would look like:
import mockAxios from 'axios'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
// for some reason i need this to fix reducer keys undefined errors..
jest.mock('../../store/rootStore.ts')
// you need the 'async'!
test('Retrieve transaction data based on a date range', async () => {
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore()
const mockData = {
'data': 123
}
/**
* SETUP
* This is where you override the 'post' method of your mocked axios and return
* mocked data in an appropriate data structure-- {data: YOUR_DATA} -- which
* mirrors the actual API call, in this case, the 'reportGet'
*/
mockAxios.post.mockImplementationOnce(() =>
Promise.resolve({ data: mockData }),
)
const expectedActions = [
{ type: REQUEST_TRANSACTION_DATA },
{ type: RECEIVE_TRANSACTION_DATA, data: mockData },
]
// work
await store.dispatch(reportGet())
// assertions / expects
expect(store.getActions()).toEqual(expectedActions)
expect(mockAxios.post).toHaveBeenCalledTimes(1)
})