Sending data with token does not work (POST request) - javascript

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}`} });

Related

js with express and prisma- delete function is still triggering insert (prisma create function on server side)

I am using express with js to delete a record from my azure sql database (prisma is the orm). The post method worked on the leads route. The delete did not work...it is posting empty record to Leads table rather than triggering the delete function on the server side:
--Client Side Script
document.querySelector('#delete_leads_form').addEventListener('submit', function(e){
e.preventDefault();
const inputs = document.querySelectorAll('#delete_leads_form input, #delete_leads_form select')
const payload = {};
inputs.forEach(input=>{
payload[input.name] = input.value
})
async function deleteReq(){
try {
const response = await fetch('https://hh-events-internal.herokuapp.com/lead', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(payload)
} )
const responseJson = await response.json()
console.log('response', responseJson)
} catch (error) {
console.error(error)
}
}
deleteReq()
})
I have tried changing the client side method to DELETE, and no luck.

How to avoid the field changing in Postman?

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

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