I am trying to perform a request which is successful in Postman:
https://ad2zu2nol06:827xhabn112#domain:1011/index.php?action=/v1/installations/7/plugins
This GET request works fine within Postman, however, when I use Axios to create the same request:
let response = await axios.get(url, {}, {
auth: {
username: 'ad2zu2nol06',
password: '827xhabn112;'
}
});
I get a 401 not authorized, I've tried everything and cannot figure it out, there is no CORS policy issues at all.
I don't know what else to do, totally lost.
Related
I have a Next.js app and I created an endpoint to handle a webhook from a third-party payment application.
The code for that endpoint is very simple, it checks that the order was paid and updates my database:
export default async function WebhookHandler(req, res) {
if (req.method === 'POST') {
const requestData = JSON.parse(req)
if (requestData.status === "paid") {
// Code to update database
}
res.status(200).json({ received: true });
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method not allowed.');
}
}
The problem is that this webhook is falling. When I go to my payment application logs, I can see the webhook requests are going to the right endpoint, but my endpoint response is a 301 (redirect) and the payment application expects a 200.
Any ideas why Next.js is creating this redirect? I don't even know where to look for this...
After a lot of digging, I found that it was my server configuration. It was redirecting my www.site.com to site.com 🤦♂️
I have successfully added my callback url in my webhooks setup. At that time, the callback url was called successfully with proper logs and everything in the server. But when I click on the TEST button for the respective name (leadgen in this case), nothing AT ALL is being received by the server when in fact it should at least log the very first line. Note that I am using post and get.
Additional note: for NetSuite experienced developers, I am using a suitelet as the callback url for the webhook.
Thanks.
Suitelets that are available externally without login will only work if the User-Agent header in the request mimics a browser. See for example SuiteAnswers # 38695.
I ran into a similar issue, and the workaround was to proxy the request using a Google Cloud Function that simply rewrote the User Agent:
const request = require('request');
exports.webhook = (req, res) => {
request.post(
{
url: process.env.NETSUITE_SUITELET_URL,
body: req.body,
json: true,
headers: {
'User-Agent': 'Mozilla/5',
Authorization: req.headers['authorization'],
},
},
function(error, response, body) {
res.send(body);
}
);
};
I'm trying to fetch data in the browser from a Dropbox link: https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1
Using Axios this works in Node:
axios.get('https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1').then(x => {
console.log('Received correctly')
console.log(x.data);
}).catch(error => {
console.log('Error', error.message);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
}
console.log(error)
});
https://runkit.com/stevebennett/5dc21d04bbc625001a38699b
However it doesn't work in the browser (click the "Console" tab):
https://codepen.io/stevebennett/pen/QWWmaBy
I just get a generic "Network Error". I see the 301 Redirect being retrieved, which seems perfectly normal, but for some reason, it is not followed.
Exactly the same happens with D3: "NetworkError when attempting to fetch resource."
https://codepen.io/stevebennett/pen/KKKoZYN
What is going on?
This appears to be failing because of the CORS policy. Trying this with XMLHttpRequest directly fails with:
Access to XMLHttpRequest at 'https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1' from origin '...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CORS isn't allowed on www.dropbox.com itself.
In API they call without Authorization is fine.
How to set header for it?
"thanks"
let headers: Headers = new Headers({ 'Authorization': token, 'Content-Type': 'application/json; charset=UTF-8' });`
let options: RequestOptions = new RequestOptions({headers: headers});
let params: URLSearchParams = new URLSearchParams();
params.append('latitude', '23.259933');
params.append('longitude', '77.412615');
params.append('nearby', '5');
return this.http.post(baseUrl, params, options)
.map(
(response: Response)=>{
return response;
}
)
Chrome console:
Response for preflight has invalid HTTP status code 404
This happens because the browser sends the headers of your request to the server before sending the actual request (what is called preflight) so as to verify your request complies with the CORS policy that is defined in the server's configuration.
So what you need to do is double check that the server you are contacting is configured properly to accept the request as you make it.
Make sure that your backend server is accepting not only the POST request but also an OPTIONS request for the same endpoint url. The OPTIONS request should just return with the success 200 code.
On that server you probably have something like "when a user hits endpoint /abc with request type POST, then return some data". You also need something that says "when a user hits endpoint /abc with request type OPTIONS return 200 OK"
If all else fails you could try using this plugin in your browser, but keep in mind this will help only continuing development and is a band-aid solution that won't work in production of course.
I'm developing a small react node application with JWT passport for authentication. I've tested all the endpoint through postman(by passing token with authorization header) and they are working properly.
This is the call im making from the front-end
export const getUsersDetails=()=>{
console.log( localStorage.getItem('jwtToken'));
return (dispatch) => {
return axios.get('http://localhost:3030/users',
{ headers: { 'Authorization': localStorage.getItem('jwtToken') } }
).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
I have enable CORS by using the the CORS module. this is the how the network calls looks like from the browser
the authorization header looks like
authorization:[object Object], eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Should this be like authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Is this the reason why im facing this issue? How to overcome this?
I was able to solve a similar issue on a MERN stack, by configuring axios globally in the react application, by adding Bearer and one space, in front of the token that is assigned globally.
axios.defaults.headers.common['Authorization'] =Bearer ${token};
initially, it was without Bearer and i kept getting a 401 status code.
axios.defaults.headers.common['Authorization'] = token;
When you want authorization in your app, it depends on how you have done your back end. If everything is ok trough postman, show how your headers in postman look when you have tasted. I use xsrf token and here is how my request header look:
{headers:
{"Access-Control-Allow-Headers" : "*",
"X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN')}
}
Maybe you should just put "Access-Control-Allow-Headers" : "*"