I am fetching IGDB api on server because I need to go through CORS. I am using async await connected to client side. Everything works fine but I need to pass query like '/?fields=cover.*,name;limit=50;' to https://api.igdb.com/v4/games from client side, not from server. When I am adding a query to client side, it's still showing the query only from server. How I can pass this query from client side? This is my code:
api/example.js
import Cors from "cors";
import initMiddleware from "../../components/init-middleware";
const cors = initMiddleware(
Cors({
methods: ['GET', 'POST', 'OPTIONS'],
})
)
const settings = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Client-ID': 'my_client-id',
'Authorization': 'Bearer my_authorization',
},
}
const remoteServerUrl = 'https://api.igdb.com/v4/games'
export default async function handler(req, res) {
await cors(req, res)
const response = await fetch(remoteServerUrl, settings);
const data = await response.json()
res.json(data)
}
client side
const settings = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Client-ID': 'my_client-id',
'Authorization': 'Bearer my_authorization',
},
const fetchData = async () => {
let query = '/api/example/'
const response = await fetch(query + HERE I WANT TO ADD QUERY, settings);
const data = await response.json();
}
Edit:
Status Code: 308 Permanent Redirect
initMiddleware
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
export default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
Related
I've been trying to send a JSON data using fetch but the backend receives an empty object.
In my Client JS I have
const user = "company1";
const username = "muneeb";
const data = {user, username};
fetch("http://127.0.0.1:3000/users/api/login", {
method: 'POST',
body: JSON.stringify(data)
}).then((response) => {
console.log(response);
});
The server side has:
router.post('/users/api/login', async (req, res, next) => {
try {
// console.log(request.body);
const request = JSON.stringify(req.body);
let imageTitles = [];
console.log(request);
*its random from here on out but you get the idea*
await components.getImages(imageTitles);
const finalKey = imageTitles.join("");
let images = await components.output(req.body.user ,req.body.username);
res.send(components.jsonConverter(imageTitles, images)); //---Top priority
db.setPassword(req.body.user, req.body.username , finalKey);
} catch (err) {
console.log(err);
res.send(err).sendStatus(500);
};
})
A few things I have already tried :
It works perfectly in Insomnia(postman).
express.json() is present , it helped me go from undefined to blank JSON.
I have enabled cors settings.
That's it for now.
The body parser express.json will only be applied for requests with Content-Type: application/json. You have to add the content type to your fetch call:
fetch("http://127.0.0.1:3000/users/api/login", {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
I have already searched a lot, but none of the solutions found work: Cannot send content-type by axios. but if I use the postman interceptor and I 'send' the request generated by axios this time it works: the node.js / express server correctly receives the request and body-parser works normally!
React side:
const API_URL = "http://localhost:8800/auth/";
const headers = {
accept: 'application/json, text/plain, */*',
'content-type': 'application/json;charset=UTF-8'
};
class AuthService {
register(pseudo, email, password) {
return axios.post(API_URL + "signup/",
{ pseudo, email, password },
{ headers: headers})
.then(response => {
if (response.data.accessToken) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
});
}
server side
const app = express();
app.use(function (req, res, next) {
console.log( req.headers);
next();
});
app.use( bodyParser.urlencoded({ extended: true }), bodyParser.json());
Usually when I use axios I send the headers in a config variable like this and I stringify the body so it sends as JSON object and not a JS object.
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const body = JSON.stringify({arguments});
try {
const res = await axios.post(/url, body, config);
...
Here's a link to the docs for a little more reading about it:
https://github.com/axios/axios
I wanted to make a request to ADP with autho1.0a
I was able to make successful requests as I wanted in postman but not through my application.
postman screenshot
npm module used
similar post
Code I tried
Part:1 Signature generation
const crypto = require('crypto')
const OAuth = require('oauth-1.0a')
const oauthObj = {};
function hash_function_sha1(base_string, key) {
return crypto
.createHmac('sha1', key)
.update(base_string)
.digest('base64')
}
oauthObj.getSignature = async payload => {
const { consumerKey,consumerSecret,apiUrl,method} = payload;
const oauth = OAuth({
consumer: { key: `${consumerKey}`, secret: `${consumerSecret}` },
signature_method: 'HMAC-SHA1',
hash_function: hash_function_sha1,
});
const request_data = {
url: `${apiUrl}`,
method: `${method}`
}
const token = {}
// return oauth.toHeader(oauth.authorize(request_data, token));
console.log('header string-----',oauth.toHeader(oauth.authorize(request_data, token)));
return oauth.authorize(request_data, token);
}
module.exports = oauthObj;
Part 2 : Axios Call
let oauthData=`oauth_consumer_key=${consumerKey}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=${oauthTimestamp}&oauth_nonce=${oauthNonce}&oauth_version=1.0&oauth_signature=${oauthSignature}= HTTP/1.1`;
const eventData = await axios({
url:`${apiUrl}?${oauthData}`,
// url:`${apiUrl}?${oauthHeader.Authorization}`,
method:'GET',
headers:{
// ...oauthHeader,
'Authorization':'OAuth',
'Accept': 'application/json',
// "Authorization": `'OAuth oauth_consumer_key="${consumerKey}", oauth_nonce="${oauthNonce}", oauth_signature="${oauthSignature}", oauth_signature_method="HMAC-SHA1", oauth_timestamp="${oauthTimestamp}", oauth_version="1.0"`
}
});
Expected Result:
{
"code": "Gone",
"message": "Event with token 954c183f-26e0-4f9e-b452-c089aaf9842f has already been consumed."
}
Receiving error:
response: {
status: 401,
statusText: 'Unauthorized',
headers: {
What might have gone wrong ?
Try using request node package oauth option
request.get(`${apiUrl}?${oauthData}`, {
oauth: {
consumer_key: '..',
consumer_secret: '..',
},
headers: {
Accept: 'application/json'
},
}, function (err, res, body) {
console.log(body);
})
I am using "Axios" to call a WCF method that takes as parameter file information and content.
The file is read and sent as a base64 encoded string.
My issue is that when the file size exceeds a certain limit, AXIOS throws an exception: "Error: Request body larger than maxBodyLength limit".
I looked up the issue and found that all solutions suggest increasing the maxContentLength / maxBodyLength parameters in the AXIOS configuration object, but did not succeed.
Find Below an implemented test case in node.js:
var axios = require('axios');
var fs = require('fs');
var path = require('path')
var util = require('util')
let readfile = util.promisify(fs.readFile)
async function sendData(url,data) {
let params = data
let resp = await axios({
method: 'post',
url: url,
data: JSON.stringify(params),
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
// maxContentLength: 100000000,
// maxBodyLength: 1000000000
}).catch(err => {
throw err;
})
return resp;
}
async function ReadFile(filepath) {
try{
let res = await readfile(filepath,'base64')
let filename = path.basename(filepath).split('.').slice(0, -1).join('.')
let ext = path.extname(filepath)
return {data:res,fext:ext,fname:filename}
let x = 1
}
catch(err)
{
throw err
}
}
(async () => {
try {
let img = await ReadFile('Files/1.pdf')
let res = await sendData('http://183.183.183.242/EMREngineEA/EMRWS.svc/web/EMR_TestUploadImg',img)
console.log(res)
}
catch (ex) {
console.log(ex)
}
}
)();
In my case, the pdf file is 20 MB, upon running, an error is thrown.
"Error: Request body larger than maxBodyLength limit"
I tried to setting the maxContentLength: 100000000, maxBodyLength: 1000000000
as presented above, but did not succeed.
Your help is appreciated.
The maxBodyLength seems to work for me in this simple test, I upload data to a local Express server. If I try to upload more than the maxBodyLength I get the same error you're getting. So I suspect there's something more, like a redirect happening in your case that's triggering the error.
There is an issue logged for axios here that seems to reference the problem, it suggests setting maxContentLength to Infinity (as the other commenter suggests).
e.g.
maxContentLength: Infinity,
maxBodyLength: Infinity
Test code below:
const axios = require("axios");
function generateRandomData(size) {
const a = Array.from({length: size}, (v, k) => Math.floor(Math.random()*100));
return { data: a, id: 1 };
}
async function uploadData(url, size) {
let params = generateRandomData(size);
let stringData = JSON.stringify(params);
console.log(`uploadData: Uploading ${stringData.length} byte(s)..`);
let resp = await axios({
method: 'post',
url: url,
data: stringData,
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
maxContentLength: 100000000,
maxBodyLength: 1000000000
}).catch(err => {
throw err;
})
console.log("uploadData: response:", resp.data);
return resp;
}
uploadData("http://localhost:8080/upload", 10000000);
Corresponding server code:
const express = require("express");
const port = 8080;
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json({limit: '50mb'}));
app.post('/upload', (req, res, next) => {
console.log("/upload: Received data: body length: ", req.headers['content-length']);
res.json( { status: 'ok', bytesReceived: req.headers['content-length']});
})
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
I'm using node.JS with request module.
My problem is, I need to authenticate the user on every request because the session is destroyed outside of the .then((response) => {}) block.
How is it possible to save the created session in a class for later use?
I tried out everything without success.
Here is a not working code snippet
login() {
const getLoginUrl = 'https://www.demourl.com/'
const postLoginUrl = 'https://www.demourl.com/account/login/'
rp({
url: getLoginUrl,
jar: this.cookieJar,
method: 'GET'
})
.then((body) => {
var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];
var args = {
url: postLoginUrl,
json: true,
method: 'POST',
data: {
username: this.username,
password: this.password
},
headers: {
'method': 'POST',
'path': '/account/login/',
'cookie': 'csrftoken=' + csrftoken,
},
jar: this.cookieJar,
resolveWithFullResponse: true
}
rp(args)
.then((response) => {
//Here is a valid session
//But how can I use this session in different functions?
console.log('Post demourl.com/account/login success');
})
.catch((error) => {
console.log('Post demourl.com/account/login error: ', error);
});
})
.catch((error) => {
console.log('Get demourl.com error: ', error);
});
}
you should use this function as a middleware and then attach what ever you want to attach in to your req
try in you main script do
'use strict'
const express = require('express');
const login = require('./login');
const app = express()
app.use(login);// use this if you want all your routes to check login or put it in a specific route
app.get('/', (req,res)=>{
//this route is only for loged in users
});
const server = http.createServer(app).listen(process.env.PORT);
module.exports = app;
and in your login script
const login = (req, res, next) => {
const getLoginUrl = 'https://www.demourl.com/'
const postLoginUrl = 'https://www.demourl.com/account/login/'
rp({url: getLoginUrl, jar: this.cookieJar, method: 'GET'})
.then((body) => {
var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];
var args = {
url: postLoginUrl,
json: true,
method: 'POST',
data: {
username: this.username,
password: this.password
},
headers: {
'method': 'POST',
'path': '/account/login/',
'cookie': 'csrftoken=' + csrftoken,
},
jar: this.cookieJar,
resolveWithFullResponse: true
}
rp(args)
.then((response) => {
res.loginResponse = response; // save the response for later use
console.log('Post demourl.com/account/login success');
next();
})
.catch((error) => {
console.log('Post demourl.com/account/login error: ', error);
return res.send(error) //send the error
});
})
.catch((error) => {
console.log('Get demourl.com error: ', error);
return res.send(error) //send the error
});
}
module.exports = login
I never see this.cookieJar being defined. Make sure it's initialized somewhere:
this.cookieJar = request.jar();
If you only use a single cookieJar in your application, you could also use Request's global cookie jar by setting the option jar to true:
// Either by setting it as the default
const request = require('request').defaults({jar: true});
// Or by setting it on each request
request('www.example.com', { jar: true });