I am trying below javascript code to subscribe on mailchimp. flow wise working good but i am getting error like not authorize because may be i am not passing api key correctly. please help to solve my issue
var request = new Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
})
});
// Now use it!
fetch(request).then(function (data) {
console.log(data);
});
You need to add your authentification details with your username and api key. You can do it with the auth parameter:
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
Just add that to your request object:
Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
}),
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
});
I looked at the documentation in the getting started section of the developer mailchimp api: here and I converted the curl examples to javascript code using this page. Let me know if it worked.
Related
I want to send a post with fetching. But I get 401 error: www-authenticate: Bearer error="invalid_token".
I am using Userfront.accessToken() but It did not work.
How can I get accestoken for bearer authentication?
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${Userfront.accessToken()}`,
},
}).then((res) => res.json());
};
Note:
console.log(`Bearer ${Userfront.accessToken()}`);
Bearer [object Object]
Can you try this? I see this from https://userfront.com/guide/auth/
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
JSON.stringify(Userfront.accessToken()) please stringify that object to understand what is going on there then if there is accessToken returning from that function put that string.
I just realized in the doc;
To handle a request like this -Userfront.accessToken()-, your backend should read the JWT from
the Authorization header and verify that it is valid using the public
key found in your Userfront dashboard.
https://userfront.com/guide/auth/
fetch('https://api.example.com', {
method: 'GET'
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
});
Thank you all for your answers.
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
In this application, token gets a different name.
When I look from inspects, I use it and it works!
Sorry for this title but i really need hlp. I don't know why that's not working and i searched a lot.
So I'm working with Spotify Api and I want to access to the Access_Token. The documentation says you have to do like that: Spotify Documentation
And I m requesting like this :
fetch ('https://accounts.spotify.com/api/token', {
method: 'post',
body: {
code: code,
redirect_uri: redirectUri,
grant_type: 'authorization_code'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic ' + btoa(clientId+':'+clientSecret)
},
json: true
})
But that's answering this:
Error
I checked and error 400 means "Bad Request".
Have u got an idea? Thanks for helping !
Looking at your error, no body was received. You have to send it as a json string:
let body = {
code: code,
redirect_uri: redirectUri,
grant_type: 'authorization_code'
}
fetch ('https://accounts.spotify.com/api/token', {
method: 'post',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic ' + btoa(clientId+':'+clientSecret)
},
json: true
})
I am trying to add couple of image attachments in google api, I am not able to find any kind of solution for it, though I am able to send mail without it, can any one help on adding attachments.
const encodedMail = btoa([
`From: ${guest_email}\r\n`,
`To: ${toHotel}\r\n`,
`Subject: ${fullname} Sent Mail\r\n\r\n`,
`Hello There\n\n I have Just Mailed, Please find my details\n\n Name: ${fullname}\n
Phone: ${phone}\n `
].join('')).replace(/\+/g, '-').replace(/\//g, '_');
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify({
'raw': encodedMail
})
});
if (response) {
console.log(response)
}
Help would be really appreciated.
I want to call an API for register from method in React. Below is my javascript code :
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: "hugh.daniel#gmail.com",
name: "Hugh Daniel",
password: "1234"
})
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
And this is my controller
[HttpPost]
public ResponseModel RegisterByEmail([FromBody]UserModel user)
{
return _accountService.RegisterEmail(user);
}
But I always get these errors
I tried to add mode: 'no-cors' in my javascript code, but it makes Content-Type set to plain.
The API is working if I tested it using Postman like this
You need to combat CORS first of all. You can't make API requests against a different domain:port than the one from which it was served by development server. Are you using Webpack in your project? If yes, the easiest way is to set up API proxy by the Webpack configuration. See the doc. Something like this:
// webpack.config.js
devServer: {
port: 3030,
proxy: {
'/api': {
target: `http://localhost:5001`,
secure: false
}
}
}
Now you have to remove host:port from fetch address param and also I would add Accept header to the request settings:
fetch('/api/Account', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// ...
}
)
try this
[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]
public class TestController : ControllerBase
{}
In js:
await fetch(this.url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
Sourse: https://pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller
Do not use JSON.stringify in the body for sending a request and following code will do the work.
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: {
email: "hugh.daniel#gmail.com",
name: "Hugh Daniel",
password: "1234"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I've been developing a mobile complement to my web application built with Rails. Using Fetch API, I keep getting the notice "Can't verify CSRF token authenticity".
export const login = (user) => {
fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({user})
})
// promise handling
}
Edit: Managed to get it to work but I still don't really understand why. If anyone has the same problem, this is how I resolved it. I managed to get the form_authenticity_token from my rails application and saved it as a variable that I then passed to the function. Haven't tested removing the credentials key.
export const login = (user, token) => {
return fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ user, authenticity_token: token })
})
You need to add CSRF token in headers or disable / remove CSRF on cross domain request.
export const login = (user) => {
fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({user})
})
// promise handling
}
When working with Django backend you should set:
'X-CSRFToken': csrf_token // not 'X-CSRF-Token' !!!
in your JS request headers.
Environment:
To set the token on the backend side, use:
{% csrf_token %} <!-- put this in your html template -->
And then, to get the token in the JS code:
const csrf_token = document.getElementsByName('csrfmiddlewaretoken')[0].value;