我一直在尝试创建一个 React 站点,它会从 API 获取 GET 响应并将其打印到我的 .html 文件中。我已经成功地正确获取了文件,但无法访问服务器发送给我的 JSON 数据。
如果我在 Fetch 请求中使用 no-cors,我会得到一个几乎不包含任何内容的不透明响应,但如果我转到开发人员工具,我可以在那里找到我的数据并读取它。如果我确实使用 cors,几乎同样的事情。我收到 403 错误,但我的数据位于浏览器内存中,但我的代码未将其打印出来。我可以在开发者工具中找到网络的回复。
为什么服务器给我一个错误,但我仍然得到我的数据?如果它在浏览器中,我该如何访问它?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
Run Code Online (Sandbox Code Playgroud)
编辑:尝试建议后出现错误图像
https://i.stack.imgur.com/wp693.png
我正在尝试为更改密码的 React 模块编写单元测试,但我无法在括号中执行代码。我已经为模块 MyAPI 编写了一个模拟,模拟代码执行得很好,并且使用 console.log("something") 我可以在控制台中看到输出。
但是,我无法让代码在 .done(function (data) 之后运行。这很可能是因为模拟正在用它自己的代码替换那些代码。
我知道一种选择是使用像 Nock 这样的假服务器,但除非必须,否则我不想将其变成集成测试。
我正在尝试测试的代码:
const MyAPI = require('../../my_api.js');
submitChangePasswordFormEvent(event) {
const self = this;
const params = {};
event.preventDefault();
event.stopPropagation();
params.current_password = this.refs.current_password.getValue();
params.passwordFirst = this.refs.passwordFirst.getValue();
params.passwordSecond = this.refs.passwordSecond.getValue();
MyAPI.my_api('/api/change_password/', params)
.done(function (data) {
// This code i would like to run but can't
const elem = <Success>{t(['settings',
'passwords_changed'])}</Success>;
self.setState({ pwerror: null, pwsuccess: elem });
self.refs.current_password.value = '';
self.refs.password1.value = '';
self.refs.password2.value = '';
})
.error(function (errors) {
// …
Run Code Online (Sandbox Code Playgroud)