我是ReactJS的新手,我正在尝试构建需要使用mailchimp的应用程序,以便用户可以订阅新闻通讯。我需要使用axios发出请求吗?有人可以指导我吗?我在哪里放置我的api密钥?我在下面的代码中正确吗?我将我的mailchimps用户名放在“用户名”中,并将apikey放在“xxxxxxxxxxxxxxxxxxx-us16”中,但是,我收到401错误,表示未授权,但我的控制台的确显示了Fetch Complete:POST,但没有发现错误。
import React, {Component} from 'react';
import './Subscribe.css';
class Subscribe extends Component {
sub = () => {
let authenticationString = btoa('username:xxxxxxxxxxxxxxxxxxx-us16');
authenticationString = "Basic " + authenticationString;
fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
mode: 'no-cors',
method: 'POST',
headers: {
'Authorization': authenticationString,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email_address: "somedude@gmail.com",
status: "subscribed",
})
}).then(function(e){
console.log('complete')
}).catch(function(e){
console.log("fetch error");
})
};
render () {
return(
<div>
<button onClick={this.sub}> subscribe </button>
</div>
);
};
};
最佳答案
在文档中,curl示例使用--user
标志。使用this将curl命令转换为等效的js代码,您需要在fetch的option对象上具有'auth'属性,以使其起作用。
fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
email_address: "somedude@gmail.com",
status: "subscribed",
},
auth: {
'user': 'username',
'pass': 'xxxxxxxxxxxxxxxxxxx-us16'
})
})