I won't have network for the following days.
My web app is made of a django back and a react front (with axios for my request). About twenties requests are made from my front to my back. Is there an easy and quick way to save my requests and then mock them. I will work only on front side.
I cannot run django back on my laptop, I cannot mock my requests on back side.
I think I need sommething like this:
$ ls mocked_request
index.js
user.json
modules.json
cart.json
products.json
product1.json
product2.json
...
$ cat mocked_request/index.js
// {endpoint: res}
export default {
user: './user.json',
modules: './module.json',
...
}
$ cat http.js
import 'axios';
import mock from './mocked_request';
mock = // here something to intercept axios request and return my mocked data
export default mock;
then in my files replace import axios by import axios from './http'
Is there a simple way do achieve this. If so, how can I set up my mocked axios ?
Use axios-mock-adapter that allows to easily mock requests.
Use Mock Service Worker - Mock by intercepting requests on the network level. Seamlessly reuse the same mock definition for testing, development, and debugging.
Use miragejs - Mirage is a JavaScript library that lets frontend developers mock out backend APIs.
Related
I am trying to mock useLazyQuery hook response from Apollo client in storybooks. It works fine if we try to mock the query following the official docs but could not find a way to mock useLazyQuery response
I am working on my nextjs project under docker, and when using getStaticProps my backend api is not available(which is also under docker). So I connected frontend to backend via networks and if i hardcode api for ssr request it works. But when i try to utilize serverRuntimeConfig and publicRuntimeConfig so i could switch between them depending on where code is being ran I get {} for serverRuntimeConfig. However publicRuntimeConfig is fine and i can access api from it.
My next.config.js is:
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
baseUrl: 'http://localhost/api/v1',
},
serverRuntimeConfig: {
// Will only be available on the server side
baseUrl: 'http://backend_nginx_1/api/v1/',
},
am I missing something ?
This will sound dumb, but I spent 2 hours seeing the empty file been recognized by the system and just seeing {}.
Now... restarting the server, gives you access to the content of the file.
That was my solution.
And it was not included in the documentation.
https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration
I am new to this. So please help me. I want to ask some questions about the sapper. I have to create separate backend API in Polka (express any framework) or I can use same Polka(express) for backend? Do i have to validate requests through the same polka server? (right now I am using pug template engine with express).
A separate backend isn't required. Sapper is the backend and the frontend.
To define a backend endpoint, add a .js files to the routes folder:
// src/routes/blog.js
import db from '...'
// defines a route `GET /blog`
export async function get(_req, res) {
const posts = await db.getPosts()
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(posts))
}
For more information: https://sapper.svelte.dev/docs/#Server_routes
Middleware can also be added by modifying src/server.js.
I am building a react app, and in it I am retrieving data from a third party site which requires me to send the API key in the header using 'X-Auth-Token'.
Currently I am making this request using fetch() api from the clientside js files.
I understand this is bad practice and I should hide my api key, so this is what I am trying to do but am finding it hard to understand how all the components fit together in this puzzle...
I have followed a tutorial and now have a create-react-app project listening locally on port 3000, and an express server (using express.router()) listening locally on port 9000.
I want to make the api request to the third party from the express server, and then send that to the front end.
using express.router(), how would i make a request to a third party that includes my api key, and then send that on to the front end?
when i eventually host this project (i am hosting on heroku), instead of the front end making a fetch request to port9000 to retrieve the data from the express server request, what url should it be listening to? - I think i lack understanding when it comes to this part.
You are on point, you should use like a middleman to retrive your data to your frontend. There are couple of implementation of course. Personally I like the serverless approach, using AWS lambda functions for it. But back to your approach. I would retrive the data using probably the axios module, very easy and straightforward. You can pass the x-auth-token header to the instance
const express = require('express');
const axios = require('axios');
const app = express()
const axiosInstance = axios.create({
baseURL: '<some-domain>',
headers: { 'X-Auth-Token' : '<some-token>'}
});
app.get('/data', async(req, res, next) => {
try {
const response = await axiosInstance.get('/<path>');
// process your data and send back to the user
} catch (error) {
// handle if you got an error
}
})
It is just a showcase, I assume your application looks different, but I think you got some direction from this snippet.
I would hide the token to an environment variable.
When you deploy your server to heroku you are going to get an url, and in your front-end you can replace the url easily and deploy it.
Environment variables will help you in both cases. You can use dotenv library. The code examples are simplified to focus on your issue.
Assuming your React app makes a request to a back-end endpoint (localhost:9000/endpoint) which will be requesting data from the third party service (in this case using got library), you will get the auth key from environment variable:
require('dotenv').config(); // init env vars
const got = require('got');
const express = require('express');
const router = express.Router();
// getting API key from env variable
const apiKey = process.env.AUTH_KEY;
// GET localhost:9000/endpoint
router.get('/endpoint', async (req, res) => {
// requesting data from 3rd party service
const response = await got('https://thirdpartyservice.com/api', {
headers: {
'x-auth-token': apiKey, // the auth token header
json: true, // assuming response will be "application/json"
},
});
// passing data to React
res.json(JSON.parse(response));
});
You should store the back-end service URL in an environment variable as well. You might have two .env files for development and production environments respectively:
Development:
# .env file on your localhost
AUTH_KEY = <your_secret_key>
API_URL=localhost:9000/
Production:
# env vars on heroku
AUTH_KEY = <your_secret_key>
API_URL=<api_server_name>.herokuapp.com/
And passing the URLs to your React app:
require('dotenv').config(); // init env vars
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// your api server URL from env vars
const apiUrl = process.env.API_URL;
// pass the api URL to your React app
ReactDOM.render(
<App apiUrl={ apiUrl } />,
document.getElementById('root'),
);
I started a project with my raspberry pi running an electron App where I need to get the actual weather from an open weather API. I am totally new to electron and not that experienced in Javascript. So I am stuck with getting the Data from the weather API into the App. I can request the Data as JSON or XML data. I tried out different ways I thought it might work but they all failed. So could someone tell me how to get API Data into electron in general?
The easiest way to start with API requests is to use axios.
After setting up the project (you can follow Getting Started), follow these steps:
Install Axios npm install --save axios
Create main.js in your project's folder.
Load main.js inside index.html somewhere before </body>.
Put the JavaScript code inside main.js
const axios = require('axios');
function fetchData() {
// you might need the next line, depending on your API provider.
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.post('api.example.com', {/* here you can pass any parameters you want */})
.then((response) => {
// Here you can handle the API response
// Maybe you want to add to your HTML via JavaScript?
console.log(response);
})
.catch((error) => {
console.error(error);
});
}
// call the function to start executing it when the page loads inside Electron.
fetchData();