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.
Related
I have 2 apps on vercel - one is nextjs, the other is FastAPI in python. The nextjs node api needs to get some data from the FastApi app.
I keep getting this content-header mismatch. What am I missing?
cause: RequestContentLengthMismatchError: Request body length does not match content-length header
at AsyncWriter.end (node:internal/deps/undici/undici:8417:19)
at writeIterable (node:internal/deps/undici/undici:8327:16) {
code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
}
My post request in node API:
const body = JSON.stringify({ data: value })
const response = await fetch(`${FAST_API_HOST}/api/data`, {
method: 'POST',
headers: {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json',
'Content-Length': body.length.toString(),
'Connect': 'keep-alive',
},
body
})
.then(async res => {
if (res.status === 200) return res.json();
else throw new Error(await res.text())
})
Having made a successful request to https://api.heroku.com/sources, I'm now attempting to upload a file to the put_url returned.
In postman this is working a treat. However, when I attempt to do the same in Axios no good. I've attached a screenshot of the postman with the 200 status.
So far I've the following....
const data = fs.readFileSync(zipPath, 'utf-8');
var config = {
method: 'put',
url: put_url,
headers: {
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type': 'text/plain; charset=utf-8',
'Content-Length': Buffer.byteLength(data),
},
data,
};
await axios(config);
Which results in the following error SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method
I've played around with the encoding, and content types (pretty much stabbing in the dark tbh)
Annoyingly, I've got it working with this:
const post_data = fs.readFileSync(path.join(__dirname, 'compare-api.tar.gz'));
const options = {
method: 'PUT',
hostname: host,
path: put_url.substring(httpHost.length),
headers: {
Host: host,
'Accept-Encoding': 'gzip, deflate, br',
'Content-Length': Buffer.byteLength(post_data),
},
};
const req = https.request(options, function (res) {
res.on('data', function () {
// Can't remove this even though it's doing nothing :(
});
res.on('end', function () {
cb(null, source_blob);
});
res.on('error', function (error) {
console.log('error', error);
cb(error);
});
});
req.write(post_data, 'utf-8');
req.end();
But I'd much rather it worked in Axios.
After what seemed like forever....
'Content-Type': ''
...did the trick!
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)
});
I am trying to create script that could post comment in my thread on steam with node and request lib. Trying to achieve by doing something like this:
const body = {
comment: 'Sometext',
count: '15',
sessionid: session_id,
}
bumpingDiscussionsPostsModule.bumpInDiscussion=async() => {
const postHeader = {
method: 'POST',
uri: urlPost,
headers: {
Cookie: cookie
},
form: JSON.stringify(body)
}
const response = await request(postHeader);
console.log(response);
}
Tho steam keeps returning me returning {"success":false}, any clues what I am doing wrong?
I was just formatting it wrong. If someone might be looking for it, this gets the job done:
const doBump = await fetch(bumpingUri, {
method: 'post',
body: `comment=${process.env.BUMP_COMMENT}&count=15&sessionid=${process.env.CONN_SESID}&extended_data=${process.env.EXTENDED_DATA}&feature2=${featureID}oldestfirst=true&include_raw=true`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'accept': 'text/javascript, text/html, application/xml, text/xml, */*',
Cookie: process.env.CONN_STRING
}
});
How can we use bearer token with POST method using npm sync-request? The sync-request resource page has the way to use authorization in GET request but not in POST request.
*******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent'
}
});
****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
json: { username: 'Name' }
});
Not sure why you would want to use sync-request which can cause timing issues but this should work with either sync-request or request
// *******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent',
'authorization', 'Bearer ' + authId
}
});
// ****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
'headers': {
'authorization', 'Bearer ' + authId
},
json: { username: 'Name' }
});
authId needs to be whatever your bearer token spoils be for your app.
I would suggest use of axis and example below:-
GET
import axios from "axios";
axios({
method: 'get',
url: url,
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}).catch((err) => {
console.log(err)
));
POST
axios({
method: 'post',
url: url,
data: JSON.stringify({orders}),
headers: {
'Content-Type': 'application/json',
'Authorization': userObj.token
}
}).then(function (response) {
console.log(response)
});
Where ubserObj.token -
Bearer Token ex: Bearer ASDF#!##!ADFASDF!##!##
This will be on the server side settings.