Following my previous post, I am getting
XHR finished loading: POST "http://partners.api.skyscanner.net/apiservices/pricing/v1.0".
seems the POST is working correctly, but for GET:
GET
http://testdomain.com:3000/undefined?apiKey=APIKEY&stops=0&duration=360&includeCarriers=ba;u2;af
404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (bundle.js:23687)
at settle (bundle.js:23657)
at XMLHttpRequest.handleLoad (bundle.js:23529)
here is that part of the code:
axios(authOptions)
.then(function(response){
console.log("response ====> ", response.headers);
console.log("--->", response.headers.Location);
/*
console.log("data is: ", response.data);
console.log("response.request.responseURL: ", response.request.responseURL );
console.log("response headers", response.headers);
console.log("location headers: ", response.headers.location);
*/
var newAuthOpts = {
method: 'GET',
url: response.headers.Location + '?apiKey=APIKEY&stops=0&duration=360&includeCarriers=ba;u2;af',
data: querystring.stringify(data),
json: true
};
axios(newAuthOpts).then(function(response) {
console.log(response);
});
})
.catch(function(error){
console.log(error);
});
return {
type: FETCH_LOCALS,
payload: data
};
I am trying to get the correct url from the header: response.headers.location, but this returns undefined, I can not find the error. can some one help please?
There's a big difference between response.headers.location and response.headers.Location - everything in JavaScript is case-sensitive. In other words both versions could co-exist and be treated as completely different properties. It's for this reason that camelCase is commonly used. In that way we can easily recognise it as an error when, for example, a property begins with a capital letter.
Related
I am using the Axios version 0.21.1.
I am sending HTTPS get request as below.
When I run below code, the #2 line inside the try block console.log... throws error.
But the error object I get in catch is empty. Not sure why log is throwing error.
try {
let getRes = await axios.get(myUrl, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes));
} catch (error) {
console.log("Error: " + JSON.stringify(error));
}
If I run the following version with #2 parameter as {} or null for axios.get.
I get the error printed in catch but I am not sure why it is failing.
try {
let getRes = await axios.get(myUrl, {}, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes));
} catch (error) {
console.log("Error: " + JSON.stringify(error));
}
The error I get is 401 Unauthorized.
From the Postman, this URL is working fine with the same Bearer token as I am using from the code.
I have even tried the below code, with the behavior same as #1 case:
let getrRes = await axios({
method: 'get',
url: myUrl,
headers: {
"Authorization": "Bearer "+token
}
});
I don't want to have request body for this get request.
What can be the issue and how to call axios.get correctly?
Your first program is the right one! But inside it's your console.log() that is not good: you cannot use the JSON.stringify() method on the getRes object returned by axios, that's why your program goes into the catch.
To display the response, either don't use JSON.stringify(), or use JSON.stringify() on the data returned by axios (which is getRes.data)
try {
let getRes = await axios.get(myUrl, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes.data));
// OR
console.log("getRes: " + getRes);
} catch (error) {
console.log("Error: " + error);
}
Note that you can't use the JSON.stringify() on the error that you got in the catch either! That's why you only had an empty object.
If you want to identify the exact cause of error, change the console.log in your try catch block. Don't try to JSON.strigify the error, rather just dump it onto the console. This will make sure to dump the error as-is, onto the console.
try {
let getRes = await axios.get(myUrl, {headers: {'Authorization': `Bearer ${token}`}});
console.log("getRes: " + JSON.stringify(getRes));
} catch (error) {
console.log(error);
}
If you still wish to get a fine grained error message, you can convert the error into string by using one of the following statements inside your catch clause:
console.log(error.message);
console.log(error.toString());
This is the full react code where I fetch the data to the server:
//process.env.NEXT_PUBLIC_DR_HOST being http://localhost:3000
await fetch(`${process.env.NEXT_PUBLIC_DR_HOST}/validate`, {
method: 'POST',
body: valBody,
headers: { 'Content-Type': 'application/json' }
}).then(res =>
{
if (res.status === 200)
{
body
? fetch(`${process.env.NEXT_PUBLIC_DR_HOST}/view/${_id}`, {
method: 'PUT',
body: body,
})
: fetch(`${process.env.NEXT_PUBLIC_DR_HOST}/view/${_id}/raw`, {
method: 'PUT',
body: valBody,
headers: { 'Content-Type': 'application/json' }
})
}
}).then(res =>
{
// console.log(res)
// window.location = res.url;
})
We are focused on the scenario where body is null (the problem appears in both). So this is the main part:
...
: fetch(`${process.env.NEXT_PUBLIC_DR_HOST}/view/${_id}/raw`, {
method: 'PUT',
body: valBody,
headers: { 'Content-Type': 'application/json' }
})
...
.then(res =>
{
// window.location = res.url;
})
The data is sent to the server, and the page redirected using the response parameter (res.redirect("/")) and the returned promise:
.then(res =>
{ //res.url = http://localhost:3000
window.location = res.url;
})
I get redirected to the specified url and practically everything works fine as it should. But here's the problem: When using the res.redirect() function (as in this case), I also get a 404 error with the message PUT http://localhost:3000/ 404 (Not Found), even if everything worked as expected, the url included in the error message being always the same as the url redirected to.
Useful:
When sending something like res.status without redirecting - nothing happens, but when sending back a message res.send("AAAA") (deos not matter if res.redirect is used) , the problem is invoked again (). So the res.redirect and res.send are causing the error. Sounds strange but the error url when using the res.send function alone is the same applied last time when res.redirect was triggered. (If I redirected res.redirect("/view"), I get and error with the "/view" url, and when replacing the line of code with res.send("anything"), the same error with the same url is printed )
I don't really know what to do
Recently, I encountered a problem while trying to issue a request using NodeJS and request-promise.
The following code is nested inside a multer call for file uploading (using nested functions / clusters.
const options = {
method: 'POST',
uri: 'URL of your choice',
body: {
//Body of the request
},
// json: true,
headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
},
}
request(options)
.then(function (response) {
console.log('Response: ', response);
})
.catch(function (err) {
console.log('Error: ', err);
});
While using the current request, without the 'json: true' property (commented out), I get the following error:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object
at write_ (_http_outgoing.js:603:11)
at ClientRequest.write (_http_outgoing.js:575:10)
at Request.write (PATH/node_modules/request/request.js:1500:27)
at end (PATH/node_modules/request/request.js:549:18)
at Immediate.<anonymous> (PATH/node_modules/request/request.js:578:7)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)
at process.topLevelDomainCallback (domain.js:121:23)
And when I turn the 'json: true' option on, the problem doesn't occur, but the remote API returns an error as it doesn't handle JSON requests/their added curly braces well.
Any ideas about getting over this issue?
Thank you.
Solved it!
As the remote host doesn't handle JSON well, and required "ordinary" POST request to be sent, I looked again inside request-promise's documentation.
By changing body{} to formData{}, and commenting out json: true, the problem was solved.
const options = {
method: 'POST',
uri: 'URL of your choice',
formData: {
//Request's data
},
}
request(options)
.then(function (response) {
console.log('Response: ', response);
})
.catch(function (err) {
console.log('Error: ', err);
});
Try Below -
url = "your url"
const options = {
url: url,
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-Charset': 'utf-8'
},
body: {
}
};
request.post(options, function (err, response, body) {
// do something with your data
console.log(response.statusCode);
console.log(body)
});
I faced similar issue, for my case, upload directory was not properly defined, make sure the path to which you want to upload file exists and is clearly defined
I'm trying to use a sentiment analysis API for some tweets I've streamed. The API in question is this: http://sentiment.vivekn.com/docs/api/. I've done this before in Python before and it worked as expected. I made a post request using the requests library and sent a JSON object with my content. The JSON object looked something like this:
{
"txt": "The content of the tweet."
}
In Python, sending the post request looked something like this:
url = "http://sentiment.vivekn.com/api/text/"
data_dict = {
"txt": "hi"
}
r = requests.post(url,json.loads(json.dumps(data_dict)))
print(r.text)
Now I'll admit I'm new to Javascript and web based programming in general, but I assume the logic should be similar in both languages. I tried using the XMLHttpRequest method but it always returned an internal server error with status code: 500.
The website works, it takes post requests and responds with the analysis, but I can't get it to work with Node. This is what I'm working with in Javascript:
const rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://sentiment.vivekn.com/api/text/',
body: {
"txt": "This is a very negative sentence, so we should get a negative analysis!"
},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function (parsedBody) {
console.log("Request received");
console.log(parsedBody);
})
.catch(function (err) {
console.log("Something went wrong\n" + err);
});
It always catches an error with status code 500. I've tried several other methods including making the request with XMLHttpRequest. Nothing seems to work. It would be great if someone could point out where I'm going wrong.
This isn't an answer, but I thought it useful to show some code that evokes a different response, which may be a clue that will help debug the problem.
I get the same response with curl:
jim-macbookpro:~/development/node/so$ curl -X POST 'http://sentiment.vivekn.com/api/text/' -H "Content-Type: application/json" -d '{"txt": "hi"}'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in theapplication.</p>
I changed the example to use 'node-fetch', and I don't get 500, rather I get 405 - METHOD NOT ALLOWED.
My suspicion is that this is a problem with the server being somehow very particular about the format of the request.
I hope this helps.
const fetch = require('node-fetch');
fetch('http://sentiment.vivekn.com/api/text', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
txt:
'This is a very negative sentence, so we should get a negative analysis!'
})
})
.then(function(parsedBody) {
console.log('Request received');
console.log(parsedBody);
})
.catch(function(err) {
console.log('Something went wrong\n' + err);
});
I'm performing a validation check on a Domain name entered by a user (eg.google.com) in my Nodejs back-end which will return either a good 200 response or bad 404 response if the domain entered was invalid.
In my React front-end I have the following code which sends the POST request:
const response = await
fetch('/new-cert', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({domainInput: domainInputValue})
});
// Show error message if domain is invalid
if (!response.ok) {
this.setState({
validDomain: false
});
} else {
this.setState({
domainAdded: domainInputValue,
domainInputValue: '', // Clear input text
validDomain: true
});
}
However, my app is getting blocked and running really slow when it gets a 404 response, how do I correctly handle this error so that my app continues to run normally after I call setState?
I've tried some try-catch blocks but couldn't get them working.