Get request sent from POSTMAN works but when sent from browser fails.
At the backend req.body is undefined even after using bodyparser middleware.
The same requet when sent from the POSTMAN works.
This is the axios call from the frontend.
await axios.get(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});
This is the backend auth handler
const isAuthenticated = (req,res,next)=>{
const accesstoken = req.body.accesstoken;
console.log(req.body);
if(!accesstoken)
{
res.json({msg:"No token provided"});
}
else
{
jwt.verify(accesstoken,process.env.ACCESS_TOKEN_SECRETE,(err,decoded)=>{
if(err)
{
res.json({msg:"Invalid token"});
}
else
next();
});
}
}
These are the cors options
app.use(cors({
origin:["http://localhost:3000","http://192.168.0.86:3000"],
optionsSuccessStatus:200,
credentials:true,
allowHeaders:["Content-Type"]
}));
The method signature you are using for axios.get applies to axios.post where the second parameter is the request body. This doesn't hold true for axios.get. You can pass query paramters as second argument of axios.get. Postman is allowing you to make GET requests with body and the server is okay with that but it isn't advised to do so. For your use case of authentication, use POST.
I guess, you meant to do axios.post:
await axios.post(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});
Related
I'm using NodeJS+express and React. The request body's expected output is "tipologia", but it actually returns an empty object.
I have looked for similar questions (there a lot of them) but none of these is useful.
client:
function CreateStudyPlan(tipologia){
return new Promise((resolve, reject) => {
fetch((URL+'/PianoStudio'), {
method: 'POST',
credentials: 'include',
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(tipologia),
}).then((response) => {
if (response.ok) {
resolve(null);
} else {
// analyze the cause of error
response.json()
.then((message) => { reject(message); }) // error message in the response body
.catch(() => { reject({ error: "Cannot parse server response." }) }); // something else
}
}).catch(() => { reject({ error: "Cannot communicate with the server." }) }); // connection errors
});
}
server:
// set-up the middlewares
app.use(morgan('dev'));
app.use(express.json());
const corsOptions = {
origin: 'http://localhost:3000',
credentials: true,
};
app.use(cors(corsOptions));
const isLoggedIn = (req, res, next) => {
if(req.isAuthenticated())
return next();
return res.status(401).json({ error: 'not authenticated'});
}
app.post('/PianoStudio', isLoggedIn, async (req, res) => {
try {
await dao.createPianoStudio(req.body, req.user.id);
res.status(201).json(req.body);
} catch(err) {
console.log(err);
res.status(503).json({error: `Database error during the creation of piano di studi for user ${req.user.id}.`});
}
});
The problem is that req.body is empty and should not be ( i am expecting it to output part-time):
The insert into the DB shows that req.user.id is ok, while req.body is an empty Object:
--
2 WORDS ON REQUEST ID AND BODY:
req.body should be the
body: JSON:Stringify(tipologia)
from the client, while req.user.id is retrieved by the session through the isLoggedIn.
2 WORDS ON HEADERS:
At first i had
headers: {
'Content-Type': 'application/json',
But it gave me CORS error:
Access to fetch at 'http://localhost:3001/PianoStudio' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So i changed the Headers to
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*"
}
as
putting 'Content-Type': 'application/json', returns again CORS error.
You should try to define tipologia as an object, in the Client:
body: JSON.stringify({tip_str: tipologia})
While in your Server, you will retrieve your tipologia as follows:
dao.createPianoStudio(req.body.tip_str, req.user.id)
I want to send Data with axios to my backend. But req.headers['Authorization'] is undefined. It is not in the header although I send it with axios.
axios:
import axios from 'axios';
const entryGroup = async (privatekey, userid) => {
try {
const options = {
headers: {
'Authorization': `Bearer ${userid}`,
'Accept': 'application/json',
},
body: privatekey
};
return axios.post('http://xxxxx:3000/entrygroup', options).then(res => res.data).catch(e => e);
} catch(e) {
return e;
}
};
export default entryGroup;
Nodejs: (all cors are enabled)
const dbf = require('../../functions/database/index');
module.exports = async (req, res) => {
const { body } = req.body;
console.log(req.headers);
};
Output from req.headers :
{
accept: 'application/json, text/plain, */*',
'content-type': 'application/json;charset=utf-8',
'content-length': '127',
host: 'xxxx:3000',
connection: 'Keep-Alive',
'accept-encoding': 'gzip',
'user-agent': 'okhttp/3.14.9'
}
Post you request like this
import axios from "axios";
const entryGroup = async (privatekey, userid) => {
try {
return axios.post(
"http://xxxxx:3000/entrygroup",
{ body: privatekey },
{
headers: {
Authorization: `Bearer ${userid}`,
Accept: "application/json",
},
}
).then(res => res.data).catch(e => e);
} catch (e) {
return e;
}
};
export default entryGroup;
Then in backend You will get it in
console.log(req.headers)
I have a JSON object that I wish to send to a server using the server's API key. I wish to have a retry count of 3 so that I can retry sending data if previous calls fail.
I am not sure whether to use 'axios-retry' or 'retry-axios'.
How do I configure the Content-Type in the header, and where do I add the API key and the data to be sent. My present code looks like this:
const axiosRetry = require('axios-retry');
axiosRetry(axios, { retries: 3 });
var data = { /*----My JSON Object----*/ };
axios.post('my url', data, {
headers: {
'Authorization': 'API_Key',
'Content-Type': 'application/json'
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
Use axios instead, it is a Promise based HTTP client for the browser and node.js
var axios = require('axios')
axios.post(url,data, {
headers: {
'authorization': your_token,
'Accept' : 'application/json',
'Content-Type': 'application/json'
}
}).then(response => {
// return response;
}).catch((error) => {
//return error;
});
I'm trying to send a simple HTTP GET request to an API. The API validates the request by looking at the x-access-token header.
However, even though I set the headers on the HTTP client, the header values are not sent.
Here's my DAL
import {HttpClient} from 'aurelia-http-client';
export class BarChartDAL {
constructor() {
this.token = '';
}
getBarchartData() {
console.log('this.token: ', this.token);
var client = new HttpClient()
.configure(config => {
config.withHeader('x-access-token', this.token);
config.withHeader('Content-Type', 'application/json');
});
return client.get('http://127.0.0.1:1337/colors')
.then(data => {
console.log('got datapoints from server: ', data.response);
return (JSON.parse(data.response));
})
.catch(err => {
console.log('failed to get a response');
return false;
});
}
setToken(token) {
this.token = token;
}
}
However, on the server, the header of the request just show
request.headers { host: '127.0.0.1:1337',
connection: 'keep-alive',
'access-control-request-method': 'GET',
origin: 'http://localhost:9000',
'user-agent': '',
'access-control-request-headers': 'content-type, x-access-token',
accept: '*/*',
referer: 'http://localhost:9000/',
'accept-encoding': 'gzip, deflate, sdch, br',
'accept-language': 'en-US,en;q=0.8'
}
As you can see, there's no x-access-token header
I've got a working example here, well working in the sense that it'll send an HTTP GET, and, if I remove authentication on the server, data will come back to the client.
How to get the PayPal access-token needed to leverage the REST Api by using node?
Once you have a PayPal client Id and a Client Secret you can use the following:
var request = require('request');
request.post({
uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"content-type": "application/x-www-form-urlencoded"
},
auth: {
'user': '---your cliend ID---',
'pass': '---your client secret---',
// 'sendImmediately': false
},
form: {
"grant_type": "client_credentials"
}
}, function(error, response, body) {
console.log(body);
});
The response, if successful, will be something as the following:
{
"scope":"https://api.paypal.com/v1/payments/.* ---and more URL callable with the access-token---",
"access_token":"---your access-token---",
"token_type":"Bearer",
"app_id":"APP-1234567890",
"expires_in":28800
}
Also, you can use axios, and async/await:
const axios = require('axios');
(async () => {
try {
const { data: { access_token } } = await axios({
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'post',
headers: {
Accept: 'application/json',
'Accept-Language': 'en_US',
'content-type': 'application/x-www-form-urlencoded',
},
auth: {
username: client_id,
password: client_secret,
},
params: {
grant_type: 'client_credentials',
},
});
console.log('access_token: ', access_token);
} catch (e) {
console.error(e);
}
})();
Modern problems require modern solutions:
const fetch = require('node-fetch');
const authUrl = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
const clientIdAndSecret = "CLIENT_ID:SECRET_CODE";
const base64 = Buffer.from(clientIdAndSecret).toString('base64')
fetch(authUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Authorization': `Basic ${base64}`,
},
body: 'grant_type=client_credentials'
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data.access_token);
}).catch(function() {
console.log("couldn't get auth token");
});
You could use PayPal-Node-SDK to make calls to PayPal Rest APIs. It handles all the authorization and authentication for you.
Here is how I get the access_token using superagent
superagent.post('https://api.sandbox.paypal.com/v1/oauth2/token')
.set("Accept","application/json")
.set("Accept-Language","en_US")
.set("content-type","application/x-www-form-urlencoded")
.auth("Your Client Id","Your Secret")
.send({"grant_type": "client_credentials"})
.then((res) => console.log("response",res.body))