HTTP request to obtain HTTP status code, but no content - javascript

I'm using axios to get the http status for URLs:
async function getUrlHttpStatus (url) {
try {
const res = await axios({ method: 'get', url })
return {
status: res.status,
statusText: res.statusText
}
} catch (err) {
return {
status: err.response.status,
statusText: err.response.statusText
}
}
}
This obviously brings back all the content from that URL as well, and if there is a lot, it can be very slow.
Is there a way to make a HTTP request, to get the HTTP status code, without downloading all the content from the URL, so it's quick..?

You can just use the HEAD method, which per definition returns just the Head (i.e. Status code) and no body.

The way you access error is : err.response.data.your_attribute_from_the_server
If the message from the server is in the the error object is in the message attribute
Eg : err.response.data.message
async function getUrlHttpStatus (url) {
try {
const res = await axios({ method: 'get', url })
return {
status: res.status,
statusText: res.statusText
}
} catch (err) {
return {
status: err.response.status,
statusText: err.response.data.message//here replace the message attibute with whatever attribute you've sent from the server
}
}
}

Related

javascript model in nextjs returning bad request 400 on fetch

i'm building a web application, in my web application i'm trying to creating a record by sending the data to the api endpoint, but everytime i make the request it returns a 400 bad request. I run it the same request in insomnia and everything was fine, can anybody help me to figure it out why it always return a 400 bad request on front end?
there is the code:
async createEvent() {
const requestBody = {
userId: this.#userId,
eventName: this.#name,
eventDate: this.#date
}
const createEventResponse = await fetch(`http://localhost:3001/event/create`, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(requestBody)
});
const { message } = await createEventResponse.json();
if (createEventResponse.status === 200) {
return {
flag: true,
message
}
} else if (createEventResponse.status ==- 401) {
return {
flag: false,
message
}
}
}
The error was that one of the fields in the requestBody was undefined.

Use Axios instead of Fetch with Cache API

I am successfully using fetch to download an image file and store in a custom cache:
await fetch(url).then( async (response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
I would like to switch this to axios so I can display download progress and stop the download if needed. I am able to successfully download the file:
await axios({
method: 'get',
url: url,
responseType: 'blob'
}).then( async (response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
But it returns and error: Failed to execute 'put' on 'Cache': parameter 2 is not of type 'Response'.
Referencing this question I also tried to manually create the response:
var init = { status: 200 , statusText: 'OK', type: 'cors', url };
var myResponse = new Response(response, init);
return cache.put(url, myResponse);
But it seems to override the other information and doesn't store the blob data at all:
Is axios able to create the type of response that is needed for the Cache API?
Edited to add: I've also tried changing the responseType to stream which is what fetch seems to return, but that didn't work either.

SyntaxError: Unexpected token r in JSON at position 0 on reactjs login page

I have been trying to make a login page in reactjs but it's throwing me an error in console like
SyntaxError: Unexpected token r in JSON at position 0 but I got 200 status code in network tab and also I'm getting "redirect" in both response and preview tab under the network tab.
I tried the same code(except it was if(response.ok) this time) with another server of my friend and it successfully redirects it to another page
This is the code that I've been trying: is response.data not correct for reactjs?
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(response); //nothing is showing in console for this statement
if (response.data == "redirect") {
this.props.history.push(`/verifyOtp/${this.state.email}`);
} else {
console.log("login failed");
window.alert("login failed");
}
} catch (error) {
console.error(error);
}
};
edit: I also tried it in postman and it gives "redirect" as response in postman so the api must be working fine
Your problem is in this line
const result = await response.json();
Your response is ok, everything is ok, but when you try to do response.json() and the response from the request isn't a valid json (maybe just a normal text), it will give you that error.
Because response can be a text or a json, you need to do some checking. Where is how to check if response is a json
This is kind of bad because on every request you will need to do this type of checking (transform it to text, try to parse, bla bla...), so What I recommend it you to use something better than fetch.
Axios is very good because it already do that checking.
For your example:
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options); // Fetch the resource
const text = await response.text(); // Parse it as text
const data = JSON.parse(text); // Try to parse it as json
// Do your JSON handling here
} catch(err) {
// This probably means your response is text, do you text handling here
}
}

Try/catch. Try statement is given an error even when It's not failing

I'm trying to implement try/catch on javascript with Fetch API using PATCH Method. Most of the time when the fetch success I get a 400 (Bad Request) error and I don't know why, I wonder If I'm forgetting to add an if statement inside the try statement to check the response status before jumping into the catch statement. I also created a function called retry() to not allow the user to make more than 3 failing calls.
And if I make it fail I am not able to see the numberOfRetries log updated.
const retry = async (callback, numberOfRetries) =>
await callback(numberOfRetries)
export const updateValue = async (name, active, numberOfRetries = 0) => {
try {
await fetch(`${apiUrl}/device/${name}?active=${active}`, {
method: 'PATCH',
headers: {
Accept: 'application/json',
'Content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
name,
active
})
})
console.log('ok')
} catch (error) {
if (numberOfRetries >= 2) {
return
}
console.log(`retry number ${numberOfRetries}`)
return await retry(updateValue, ++numberOfRetries)
}
}
when the fetch is successfull I get a 400 (Bad Request) error and I don't know why, it's jumping into the catch statement.
No, the catch block doesn't run. The error you see in the devtools log is because a network request failed with an HTTP error code. You can disable the log messages in the console options.
As for why you are getting a 400 code, you have to check your serverside code - it suggests you are doing the request wrong.
I wonder If I'm forgetting to add an if statement inside the try statement to check the response status
Yes, you forgot that as well. You should check for the .ok property of the response:
export const updateValue = async (name, active, numberOfRetries = 0) => {
try {
const response = await fetch(`${apiUrl}/device/${name}?active=${active}`, {
// ^^^^^^^^^^^^^^
method: 'PATCH',
headers: {
Accept: 'application/json',
'Content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
name,
active
})
})
if (response.ok) {
// ^^^^^^^^^^^^^^^^
console.log('ok')
// console.log(await response.text()) or something
} else {
throw new Error("HTTP Error "+response.status);
}
} catch (error) {
if (numberOfRetries >= 2) {
return
// ^^^^^^ should be `throw error` instead of returning undefined?
}
console.log(`retry number ${numberOfRetries}`)
return updateValue(name, active, ++numberOfRetries)
// ^^^^^^^^^^^^^ pretty surely you'll want to pass through the arguments
}
}

Node.js http request returning body/msg empty

I am trying to use the requestjs package to post data and wait for a response. But I the body response is always undefined.
var request = require('request');
request({
method: "POST",
baseUrl: "https://255.255.255",
uri: "/login",
form: {
username: "username",
password: "password",
autologin: "true"}},
function(body, msg, err){
console.log(body); console.log(msg);
})
Edit: Again, the undefined body was caused by a privacy policy.
The format for the callback is (err,response,body); maybe that is why you are getting a empty body and response.
You can refer here for details.
I think you are getting confused with Promise and non-promise request package. As per your example, $ajax returns Promiseified response and you directly get the data from the response of the ajax request. You are expecting that request package should also give you data directly, which is not correct.
Actually, you can solve your issue in two ways:
Sol. 1:
Use proper callback function arguments and you must get data in the third argument of the callback function. Such as:
var request = require('request');
request({
method: "POST",
baseUrl: "https://255.255.255",
uri: "/login",
form: {
username: "username",
password: "password",
autologin: "true"
}
},
function (error, httpResponse, body) {
if (error) {
console.error(error);
}
console.log(httpResponse.statusCode);
console.log(body);
});
Sol. 2:
Use request-promise NPM package (download it from here) and get pomisified response. For example:
var request = require('request-promise');
const getData = async () => {
return new Promise((resolve, reject) => {
const options = {
method: "POST",
baseUrl: "https://255.255.255",
uri: "/login",
form: {
username: "username",
password: "password",
autologin: "true",
resolveWithFullResponse: true, // Returns full response. To get only data don't use this property or mark it false.
}
};
// Get whole Response object.
const response = await request(options);
// Returns the Promise.Resolve or Reject based on response.
if (response.statusCode < 200 || response.statusCode > 300) {
const errorMsg = 'Error occurred while POSTing the request. Got status: ' + response.status;
console.error(errorMsg);
// Reject the promise. Should be caught.
return reject(errorMsg);
}
const responseBody = response.body;
console.log(responseBody);
// Return the response.
return resolve(responseBody);
})
}
Above implementation will return a promise for the method getData() being called.
NOTE: The statement const response = await request(options); will return whole response object if resolveWithFullResponse: true, is used in the options JSON object. If you need only response body or data don't mention resolveWithFullResponse property in the options or assign value false to it. By default the value of resolveWithFullResponse is false.

Categories

Resources