Creating and fetching authtoken with javascript from Django Rest Framework - javascript

http POST http://localhost:8000/api-auth-token/ username="saadman" password="Sakib123#"
It works fine when i run it on terminal.
Now, I am trying to implement equivalent code in javascript to fetch authtoken:
fetch('http://localhost:8000/api-auth-token/',{
method:'POST',
header:{
username: 'saadman'
password: 'Sakib123#'
}
}
But it's not working

finally this worked for me:
var raw = JSON.stringify({"username":"saadman","password":"Sakib123#"});
var requestOptions = {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: raw,
redirect: 'follow'
};
fetch("http://192.168.43.189:8000/api-auth-token/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

Related

Sending PUT request to KV Core API in Google Apps Script

I'm trying to set up GAS to send an API call to my CRM. Here is the link for the API documentation.
I'm attempting to use the code for sending a text via the API. Below is what they provided. I have changed this code to work with GAS(see further down):
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Bearer {{api_token}}");
var raw = JSON.stringify({
"message": ""
});
var requestOptions = {
method: 'PUT',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api.kvcore.com/v2/public/contact/{{contact_id}}/text", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I adapted the code provided to work with GAS. This is what I'm actually trying to run:
function kvCoreStyle(){
var myHeaders = {
"Content-Type":"application/json",
"Authorization":"Bearer {{TOKENID}}"
}
var raw = {
"message":"let me know if you get this text"
}
var requestOptions = {
"method":"PUT",
"headers":myHeaders,
"body": raw,
"redirect":"follow"
};
UrlFetchApp.fetch("https://api.kvcore.com/v2/public/contact/{{ContactID}}/text", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
Unfortunately, I keep getting an error saying "Request body must be a valid JSON string"
I have tried using JSON.stringify() on multiple portions of this and can not get it to work at all. Any advice would be appreciated!

Response data returns undefined from asp.net web api to vue.js

currently I'm fetching data from my api to front-end. I checked and my request body is arriving to server side. But after doing things when it comes to returning the token it always returns undefined data to vue.js:
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]User user)
{
var result = await _accountRepository.LoginAsync(user.username, user.password);
if (string.IsNullOrEmpty(result))
{
return Unauthorized(result);
}
Debug.WriteLine(result.ToString()); // this works and I can see the token
return Ok(result);
}
When it comes here:
methods: {
login() {
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
}).then(response => {
console.log(response.data); // this is always undefined
})
.catch(e => {
console.log(e);
});
},
}
Please help I can't see any errors here. I'm confused.
You need to call either Response.text() or Response.json() depending on what data you expect. These methods return a Promise that resolves to the data.
E.g. for JSON:
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e));

POST request generates failed to fetch

I'm having problems making a POST request through the fetch API from javascript and I get the following error: TypeError: Failed to fetch at fetchCallImpp at window.fetch
The code is the following:
const agregarCafetalDB = (nombre) => {
const data = {
"nombre": `${nombre}`,
};
const requestOptions = {
method: 'POST',
body: JSON.stringify(data),
redirect: 'follow',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
};
fetch(url, requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
btnAgregar.addEventListener('click', (e) => {
agregarCafetalDB(cafetal.value)
});
I would like you to help me solve the error thank you very much in advance
Does the same error shows in other browsers? fetch is ES6 Javascript, maybe the browser you are using doesn't support it.
fetch(url, requestOptions)
Also, make sure that variable 'url' is defined.

fetch method JavaScript

I am working on a website and I am trying to write a script which sends data once someone creates an account. But I get some errors(attached a screenshot) and can't find a way to fix them as I'm still an intern. Hopefully someone can help me.
Thank you.
if (val2 == 1) {
fetch(hookURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
body: attrString,
mode: 'no-cors'
})
.then((response) => {
//console.log('hook returned, response= ', response);
});
enter image description here
If You want to send data - use a different method ;)
Try POST instead of GET
Look at the below example from:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});

fetch on react component method with problem

Im trying to make an API CALL using fetch in a method (saveUser). API is working fine and de method is doing his work well but I dont know why the PUT doesnt work.
Here is the code:
saveUser(user: IUser) {
user = this.state.user;
let userId = user._id;
let url = `http://localhost:4200/api/update-user/${userId}`;
fetch(url, {
method: 'put',
body: JSON.stringify(user),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
debugger;
};
Here is all the code: manageUserPage
Make changes in your request like this:
fetch(url, {
method: 'PUT',
body: JSON.stringify(user),
headers: {
'Content-Type': 'application/json'
}
Let me know if the issue still persists and make sure you have enabled CORS.

Categories

Resources