首页 > 解决方案 > 未处理的拒绝(TypeError):无法获取,使用 Node.js 进行 REST

问题描述

我尝试使用 React Js 和部署在 Heroku 上的 Node.js REST api 发出请求。我得到了这个错误Unhandled Rejection (TypeError): Failed to fetch。出于某种原因,我不明白为什么会这样。

我的代码看起来像这样

import './Home.css'
import React, { useState } from 'react';
import { Link , useHistory } from 'react-router-dom';

const MyLogin = () =>{
    const[username, setUsername] = useState('');
    const[password, setPassword] = useState('');
    const history = useHistory();

    function login(){
        let item = {username , password};
        fetch('https://instagramklone-restapi.herokuapp.com/api/login',{
            method : 'POST',
            mode : 'cors',
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(item)
        }).then((response) => response.json())
        .then((responseJson) =>{
            if(responseJson.message === 'OK'){
                localStorage.setItem('userinfo', username);
                history.push('/dashboard');
            }else{
                alert(responseJson);
            }
        });
    }

    return (
        <div align="center">
            <table width="61%" border="0">
            <div className="instagramlogo">
                <img src="images/43cc71bb1b43_2-removebg-preview.png"/>
            </div>
            <div className="login_page">
                <img border="0" align="center" src="images/images-removebg-preview.png" width="168" height="70" className="InstagramLogo" />
                <div className="usernameLogin">
                    <p align="center"><input type="text" name="T1" placeholder="  Phone number, username or email" size="33" onChange ={(e) =>setUsername(e.target.value)} className="inputBox" /></p>
                </div>
                <div className="usernameLogin">
                    <p align="center"><input type="password" name="T1" placeholder="  Password" size="33" onChange ={(e) =>setPassword(e.target.value)} className="inputBox" /></p>
                </div>
                <div className="usernameLogin">
                    <p align="center"><input onClick={login} type="submit" value="Login" name="B1" class="BtnLoginClass"/></p>
                </div>
                <div className="forgotPassword">
                    <p align="center"><Link to="#">Forgot Password?</Link><font face="Arial"/></p>
                </div>
            </div>
                <div className="No_account">
                <p align="center"><font face="Arial"/>No Account? <Link to="/register">Register!</Link></p>
                </div>
                <div className="get_app">
                    <p align="center"><font face="Arial"/> Get The app</p>
                </div>
                <div className="PlayStoreAppStoreArea">
                    <td width="204">
                    <p align="center">
                    &nbsp;<input type="image" src="images/appstore.png" width="169" height="51" align="right"/>
                    </p>
                    </td>
                    <td width="204">
                    <p align="center">
                    &nbsp;<input type="image" src="images/googlePlay.png" width="169" height="51" align="left"/>
                    </p>
                    </td>
                </div>
            </table>
        </div>
    );
};

export default MyLogin;

错误看起来像这样

![9090.png]错误(https://i.postimg.cc/85h739mz/9090.png)

它应该以 json 身份验证,然后登录并导航到仪表板,但我收到错误消息。请帮忙。

编辑 我得到这个错误

Access to fetch at 'https://instagramklone-restapi.herokuapp.com/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

标签: reactjsfetch

解决方案


我修好了它。

我必须将此添加到我的 Node.JS REST api

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
 });

它就像一个魅力,我还设置了 REST api 的捕获,一切似乎都处于良好状态:) 谢谢大家


推荐阅读