How to avoid the field changing in Postman? - javascript

I'm trying to make HTTP requests to a Netsuite server and I'm using Postman to test them. Then I'm using the JavaScript code generated by Postman in VSCode and it works only the first time. If I want to make another test, I have to send it first from Postman and then copy-paste the code to VSCode again, because some fields of the 'Authorization' parameter change every time a request is sent. Is there a way to avoid this? Or should I do something different in VSCode? These are the parameters I'm using in VSCode:
'Authorization':'OAuth realm="",
oauth_consumer_key="",
oauth_token="",
oauth_signature_method="",
oauth_timestamp="",
oauth_nonce="",
oauth_version=""
oauth_signature=""',
'Cookie': ''
The ones that always change are oauth_timestamp, oauth_nonce, oauth_signature. Here's the complete code:
var axios = require('axios');
var config = {
method: 'get',
url: 'https://url',
headers: {
'Authorization':'OAuth realm="",
oauth_consumer_key="",
oauth_token="",
oauth_signature_method="",
oauth_timestamp="",
oauth_nonce="",
oauth_version=""
oauth_signature=""',
'Cookie': ''
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});

try with async function:
something like this:
async function(){
try {
const userToken = await AsyncStorage.getItem('userToken');
let {data} = await axios.get("http://104.248.125.152:1337/api/tasks-category/format",{
headers:{
Authorization: `Bearer ${userToken}`
}
})
if (data) {
let info = data.data
setTasks(info)
}
} catch (error) {
console.log(error)
}
}

Related

Sending data with token does not work (POST request)

I send a data with Post request, but error is displayed for me (this line code : console.log(e);
I gave the ‍‍token manually to test the code
It works for me in the postman, but the code below doesn't work for me:
const sendDataTab1 = async (e) => {
const token = "eyJ0eXAiOiJKV1QiL"
try {
const api = `/api/v1/test/add`
await axios.post(api,{ headers: {"Authorization" : `Bearer ${token}`} });
console.log("hihihi");
} catch (e) {
toast.error(e.response.data.error, { autoClose: 15000 });
console.log(e);
}
};
When you post via axios, second param is the data, and third param is the config (https://axios-http.com/docs/post_example)
Therefore you are sending your headers as POST data.
Maybe try:
await axios.post(api,{}, { headers: {"Authorization" : `Bearer ${token}`} });

axios GET request with form data in React JS

I want to implement the following cURL request (which is working) in react js using axios:
curl -k --request GET "BASE_URL_SERVER/sendText" --form "user_id="uidxxxx"" --form "sign_id="
I always get the same error: field sign_id not found, but technically I'm sending it, so I'm kind of desesperate.
var data = new FormData();
data.append('user_id', 'uidxxxx');
data.append('sign_id', '9');
const api = axios.create({
baseURL: BASE_URL_SERVER,
data: data,
headers: {
'Content-Type': `multipart/form-data; boundary=${data._boundary}`
},
timeout: 10000,
})
api.get('/sendText')
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
I've also tried adding '...getHeaders()' to the headers section but React says it is not a function; I've read in other posts that it has something to do with the browser
thanks in advance
ps: it is a pretty similar problem to this one, but none of the solutions worked for me
[UPDATE]
I ended up implementing it with POST, which is better for posting Form Data; no headers are needed, the browser automatically adds them:
var data = new FormData();
data.append('user_id', user_id);
data.append('sign_id', sign_id);
const api = axios.create({
baseURL: BASE_URL_SERVER,
timeout: TIMEOUT_SERVER,
})
api.post('/sendText', data)
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
You have a mistake, you try to send data via axios for POST and method is GET...
So that, You need to Change Method to be POST to can Post form data or you need to change it to url param or url path base on your api to be WORK as a GET...
Base on your curl, your case is you need a GET:
// Make a request for a user with a given ID
axios.get('/sendText?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
sendText: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
Also, you can save all config in instance and share it for all nested of write it again and again..
for example:
// Common Axios Instance Config
const axiosConfig = {
baseURL: process.env.REACT_APP_API_ENDPOINT,
};
// Create Default Axios Instace
const instance = axios.create(axiosConfig);
I think base on your example this will work, but not sure sine I'm not test it..:
var data = new FormData();
data.append('user_id', 'uidxxxx');
data.append('sign_id', '9');
const api = axios.create({
baseURL: 'https://193.146.38.4:56076',
headers: {
'Content-Type': `multipart/form-data; boundary=${data._boundary}`
},
timeout: 10000,
})
api.get('/sendText', {
user_id: 111,
sign_id: 2222
)
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
For more details view this url

Typescript removes Authorization header from POST and PATCH fetch requests

I've built an API using C# that uses JWT tokens for authorization. On the frontend I store these tokens in local storage and get them, when creating a request. When creating GET or DELETE requests, everything works fine, and using console.log() I can see that fetch options have the Authorization header added. However when using POST or PATCH methods, the Authorization header is missing immediatly after adding it to the object. Here is my request method:
const send = async (apiOptions: ApiParams): Promise<FetchReturn> => {
const accessToken = GetAccessToken()
const options: ApiOptions = {
method: apiOptions.method,
headers: {
Authorization: `Bearer ${accessToken}`
}
}
console.log(options)
if (apiOptions.data) {
options.headers = {
'Content-Type': 'application/json'
}
options.body = JSON.stringify(apiOptions.data)
}
const result = await fetch(`${getUrl()}/${apiOptions.path}`, options).then(res => res).catch(err => err)
if (!result.ok) {
if (IsExpired()) {
const refreshResult = await fetch(`${getUrl()}/api/user/refresh`, {method: 'POST', headers:{
'Content-Type': 'application/json'
}, body: JSON.stringify(GetRefreshRequest())}).then(res => res).catch(err => err)
if (refreshResult.ok) {
Login(JSON.parse(await refreshResult.text()))
return await send(apiOptions)
} else if (refreshResult.status === 401) {
Logout()
window.location.reload()
return { code: 0, text: ""}
}
}
}
const text = await result.text()
return { code: result.status, text: text }
}
I suppose that in apiParams for POST you have property 'data' assigned, and later you have if-condition that completely replaces request headers object.
Change it to:
options.headers['Content-Type'] = 'application/json';
To keep authorization in headers
The first time check your apiOptions.data
i think , its null when you call POST/Patch request
Just put console.log("...") In the if statement , Then try for resolve your Error
If your problem not resolved, put a replay under my post

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
}
}

Unable to send get request with headers using axios

Able to get the response in postman. But unable to get in axios. Getting html as response. What would be the problem?
import axios from 'react-native-axios';
var config = {
headers: {
'Content-Type': 'Application/Json',
'JsonStub-User-Key': '__USER__KEY',
'JsonStub-Project-Key': '__PROJECT__KEY'
}
};
export async function menuListByCategories() {
// simulate an asynchronous operation
const url = "http://jsonstub.com/burgers";
axios.get(url, {config})
.then((response) = > {
console.log(response.data);
})
.
catch ((error) = > {
console.log("axios error:", error);
});
}
Update: check the response of this code
You can add data: {} in config in order not to have Content-Type removed by axios. Check the answer of the question below.
Jsonstub response not showing

Categories

Resources