我正在尝试获取nytimes api来测试某些代码,但出现了相同的“ 401(未经授权)”错误。我已经尝试过在node.js上的代码,还尝试了将代码嵌入到html中,但是两次结果相同。我似乎无法找出问题所在。
我尝试使用fetch命令而不是$ .getJSON编写代码,但结果相同。我在node.js上安装了jquery npm,并在尝试将代码嵌入html文件时还引用了html中的库以及react和babel库。
class MyApp extends React.Component{
constructor(props){
super(props);
this.state = {articles: []};
}
componentDidMount(){
var url=
'https://api.nytimes.com/svc/search/v2/articlesearch.json?'
+ 'api-key=xxxxxxxxxxxxxxxxxxxxxxx'; //used the valid key
$.getJSON(url, function(data, status){
return this.setState({articles: this.parse(data)});
}.bind(this));
}
parse(results){
if(!results || !results.response){
return [];
}
var articles = results.response.docs;
var parsedArticles = [];
for (var i = 0; i < articles.length; i++){
var article = articles[i];
if (article.multimedia.find(this.isXL)){
parsedArticles.push({
id: article._id,
title: article.headline.main || 'Untitled',
imageURL:
article.multimedia.find(this.isXL).url || '#',
webURL: article.web_url || '#'
});
}
}
return parsedArticles;
}
isXL (image){
return image.subtype === 'xlarge';
}
render(){
return this.state.articles && (
<div className = 'articles'>
{this.state.articles.map(function(article){
return <Article article={article} key=
{article._id} />;
})}
</div>
);
}
}
var Article = function({article}){
var imgURL = 'https://static01.nyt.com/' + article.imageURL;
return(
<div className='article'>
<a className='article-link' href={article.webURL}>
<img className = 'article-image'
title = {article.title}
src = {imgURL} />
</a>
</div>
);
}
ReactDOM.render(
<MyApp />, document.getElementById('container')
);
每次在控制台上都得到相同的错误
获取https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=xxxxxxxxxxxxxxxxxxxxx 401(未经授权)