Problem importing module using express Not Using Bundler - node.js

Im building a application using express and I dont want to use a bundler. When I import the axios module it gives me the next error: "Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../"."
I also made a repository of the entire project so far here: https://github.com/klaus4323/Natours-Nodejs.git
The code where I want to use axios is in the login.js (I am doing the nodejs online class of Jonas Schemetmann) file:
import axios from 'axios';
import { showAlert } from './alerts.js';
export const login = async (email, password) => {
try {
const res = await axios({
method: 'POST',
url: 'http://127.0.0.1:3000/api/v1/users/login',
data: { email, password },
});
if (res.data.status === 'success') {
showAlert('success', 'Logged in succesfully');
window.setTimeout(() => {
location.assign('/');
5000);
}
catch (err) {
showAlert('error', err.response.data.message);
}
};
export const logout = async () => {
try {
const res = await axios({
method: 'GET',
url: 'http://127.0.0.1:3000/api/v1/users/logout',
});
if ((res.data.status = 'success')) location.reload(true);
catch (err) {
showAlert('error', 'Error logging out. Try Again!');
}
};

Use like this
import * as axios from 'axios'

Related

how to set headers in axios patch request in react js

Can someone tell me what mistake I am making or tell me how to set the header in axios patch request. when I am running the API through postman, everything is working fine but when I connect it with the front end, an error comes up saying that the JWT is not provided on the backend
here is the frond end code :
import React, { useEffect } from 'react';
import { useParams } from 'react-router';
import axios from 'axios';
const Loader = () => {
const parmas = useParams();
const { id } = parmas;
console.log(id);
useEffect(() => {
const fetchBags = async () => {
try {
const res = await axios.patch('http://localhost:4001/public/verify', {
headers: {
'Content-Type': 'application/json',
Token: id,
},
});
console.log(res);
console.log('CBM', { res });
} catch (error) {
console.log(error);
}
};
fetchBags();
}, []);
return <div>this is loader</div>;
};
export default Loader;
below is my backend code:
export const verifyUser = async (data) => {
const token1 = data.header("Token");
try {
const verified = jwt.verify(token1, getTokenSecret());
console.log(verified)
await userModel.verifyUser(verified);
return {
message: "success",
};
} catch (error) {
console.log(`Auth Service > verifyUser > ${error.toString()}`);
throw error;
}
};
this error is comming:
Error
From docs
axios.patch(url[, data[, config]])
As you can see you pass config in 3rd argument not 2nd.
const res = await axios.patch(
'http://localhost:4001/public/verify',
{}, // data (2nd argument)
{
headers: {
'Content-Type': 'application/json',
Token: id,
},
} // config (3rd argument)
)

How to get data from api using axios

Postman gets the data correctly but axios get the wrong data, it receives the "Not found" but there is a record in DB.
react hook:
import axios from "axios";
import {useEffect, useState} from "react";
export default function useRoom(roomName) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [room, setRoom] = useState({})
useEffect(() => {
setLoading(true)
axios({
method: "POST",
body: {
"roomName": "test1"
},
withCredentials: true,
url: "http://localhost:4444/room",
}).then(res => {
setRoom(res.data)
console.log(res)
setLoading(false)
}).catch(e => {
setError(e.toString())
setLoading(true)
})
}, [roomName])
return {
error,
room,
loading
}
}
NODE JS:
app.post('/room', (req, res) => {
Room.findOne({roomName: req.body.roomName}, async (err, doc) => {
if (err) throw err;
if (!doc) res.send("No Room Found");
else {
res.send(doc);
}
})
})
Postman receives the data but the axios doesn't
I have the data in my db
What I get in the browser console:
How I use my hook:
If someone knows how to solve this issue please let me know
I'm not sure but maybe you should use 'data' instead of 'body' :
axios({
method: "POST",
data: { // <--- HERE
"roomName": "test1"
},
withCredentials: true,
url: "http://localhost:4444/room",
})

OIDC Callback: axios calls not working inside router.get

I cannot get my api to work with my express server with OAuth2 logic, I always get an error since I had
res.render i commented it out now the whole part is router.get does not work for axios.post inside it. Here is the code snippet:
mport {Request, Response, Router} from 'express';
import {writeFile, readFile, unlinkSync, unlink} from 'fs';
import {URLSearchParams} from 'url';
import axios from 'axios';
import qs from 'querystring';
const router: Router = Router();
...
//OIDC Callback
router.get('/callback', async function ({ query }, res, next) {
console.log("In Callback...");
if (query.error) {
const description = query.error_description;
return res.render('error', {
error: description
});
}
try {
const code = query.code;
const basicAuthHeader = Buffer.from(`${settings.clientId}:${settings.clientSecret}`).toString('base64');
console.log("Inside callback...token details: "+ settings.clientSecret);
const main_token = (await axios.post(metaData.token_endpoint, qs.stringify({
grant_type: 'authorization_code',
redirect_uri: settings.callbackUrl,
code,
scope: settings.scopes
}), {
headers: {
'Accept': 'application/json',
'Authorization': `Basic ${basicAuthHeader}`,
'Content-Type': 'application/x-www-form-urlencoded'
}
})).data;
const checkAURL = await needsAURL();
if (checkAURL) {
res.redirect(checkAURL);
} else {
// res.render('index', settings);
console.log("inside else...");
}
} catch (e) {
console.log("Error..Need organization access");
// return res.render('error', {
// error: e
// });
}
});
I am pretty sure it is because of express router settings but I cannot fix this. If i make a axios.get inside router.get it works. But in this case I cannot do that.
Did I use express router correctly? Because I have never used it before.

export function with promise in nodejs

I am trying to import a function from an external file I have, which contains a promise.
The resolution of the promise is what should be returned, but I get an error message:
The requested module './functions.js' does not provide an export named 'getOkapiToken'
The POST request works fine when I run it directly in the server, but I need it in a separate file as it will be used by several different files in the future.
This is also the first time I'm using promises, so I'm not sure I handled it properly (though I can't get any errors registered until I deal with the first one).
The functions.js file is built as follows:
import post from 'axios';
export function getOkapiToken(url, user, password) {
//Get username and password for API
const auth = {
"username": user,
"password": password
};
//Create headers for POST request
const options = {
method: 'post',
data: auth,
headers: {
'Content-Type': 'application/json',
'Content-Length': auth.length,
'X-Okapi-Tenant': 'diku'
}
};
//Make API post call
post(url+':9130/authn/login', options)
.then(response => {
return(response.headers['x-okapi-token'])
}).catch((err) => {
return(`There was an error 2: ${err}`)
})
}
And I try to import it as follows:
import { getOkapiToken } from './functions3.js'
import settings from './jsons/config.json';
let OkapiKey = await new Promise((resolve,reject) => {
//Call function to make API post call
let keytoken = getOkapiToken(settings.url,settings.userauth,settings.passauth)
console.log(`There was an error: ${keytoken}`)
if (keytoken.length == 201) {
resolve(keytoken)
} else {
reject('There was an error')
}
})
OkapiKey.then((data) => {
console.log(data)
})
.catch((err) => {
console.error('I have an error:'+err.code);
})
There are three ways to handle asynchronous task in Javascript and wit Node.JS
Pass in a Callback to run in the asynchronous code
Use a Promise that will either resolve or reject the promise
Use the async keyword in front of the function and place await in front of the asynchronous code.
With that said I was able to get the code to work by running a simple node server and I modified your code just a bit to get a response back from the server.
index.js
const { getOkapiToken } = require('./functions.js')
const settings = require('./settings.json')
var OkapiKey = getOkapiToken(settings.url,settings.userauth,settings.passauth)
OkapiKey
.then((data) => {
console.log('I have data'+ data.toString())
})
.catch((err) => {
console.error('I have an error:'+err.code);
})
functions.js
const post = require('axios');
const getOkapiToken = (url, user, password) =>
new Promise(function (resolve, reject) {
//Get username and password for API
const auth = {
"username": user,
"password": password
};
//Create headers for POST request
const options = {
method: 'post',
data: auth,
headers: {
'Content-Type': 'application/json',
'Content-Length': auth.length,
'X-Okapi-Tenant': 'diku'
}
};
post('http://localhost:3000/', options)
.then(response => {
resolve(response.data)
// if (response.headers['x-okapi-token']) {
// resolve(response.headers['x-okapi-token']);
// } else {
// reject((error));
// }
}).catch((err) => {
console.error('Response Error:'+err)
})
})
exports.getOkapiToken = getOkapiToken;

Call server-side function from ReactJS component

I'm trying to implement a payments system in my ReactJS app that requires server-side code.
I have several questions:
How do you connect a ReactJS app so it can communicate with server-side code?
How would you set up a function in the server-side code?
How would you call that function from a component in a ReactJS app?
For reference, I'm trying to integrate Stripe subscriptions. They give server-side code examples for Node, PHP, etc.
FYI: I am not trying to set up server-side rendering. When you search for server-side code in reference to ReactJS, that's just about all that comes up.
EDIT: I'm particularly interested in a NodeJS solution. I'm also using Webpack.
Just in case, it is helpful to you... I have a React UI that triggers video processing on a Django backend (I mainly use GraphQL through Apollo Client to trigger my server side functions and REST framework when file transfers are involved).
Is REST an option for you?
The middleware I use for file transfers for example:
const SERVER_URL = process.env.SERVER_URL;
const fileTransferApi = (payload) => {
const { authenticated, token, endpoint, body, contentType, method } = payload;
let config = {};
if (authenticated) {
if (token) {
config = {
method,
headers: {
'Content-Type': contentType,
Authorization: `Bearer ${token}`
},
body
};
} else {
throw new Error('No token saved!');
}
}
return fetch(`${SERVER_URL}/api/rest/v1/${endpoint}`, config)
.then((response) =>
response.text().then((text) => ({ text, response }))
).then(({ text, response }) => {
if (!response.ok) {
return Promise.reject(text);
}
return text;
}).catch((err) => console.log(err));
};
export const FILE_TRANSFER_API = Symbol('FILE_TRANSFER_API');
export default () => (next) => (action) => {
const fileTransferApiAction = action[FILE_TRANSFER_API];
if (typeof fileTransferApiAction === 'undefined') {
return next(action);
}
const { payload, types } = fileTransferApiAction;
const [, successType, errorType] = types;
return fileTransferApi(payload).then(
(response) =>
next({
type: successType,
payload: {
text: response,
message: 'ok'
}
}),
(error) => next({
type: errorType,
payload: {
error: error.message || 'There was an error.'
}
})
);
};
My store (I use Redux):
import { createStore, compose, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import ReduxThunk from 'redux-thunk';
import ApolloClientSingleton from '../network/apollo-client-singleton';
import fileTransferApi from '../middlewares/fileTransferApi';
import reducer from './reducers';
export default class Store {
constructor(history, initialState = {}) {
this.data = createStore(
reducer,
initialState,
compose(
applyMiddleware(
fileTransferApi,
ReduxThunk.withExtraArgument(ApolloClientSingleton),
routerMiddleware(history),
ApolloClientSingleton.middleware()
),
typeof window === 'object' && typeof window.devToolsExtension !== 'undefined'
? window.devToolsExtension() : (f) => f
)
);
}
}
In my actions:
export const windowsDownload = (authenticated, token) => ({
[FILE_TRANSFER_API]: {
types: [WINDOW_DOWNLOAD_REQUEST, WINDOW_DOWNLOAD_SUCCESS, WINDOW_DOWNLOAD_FAILURE],
payload: {
endpoint: 'file_transfer/download/windows',
contentType: 'text/csv',
method: 'get',
body: null,
authenticated,
token
}
}
});
This REST setup enables me to send requests (POST video, GET csv...) from my React UI to my Django server. Can't you set up some REST calls between your app and your server?

Resources