【问题标题】:× TypeError: Object(...) is not a function. Mern stack post request with fetch not working× TypeError: Object(...) 不是函数。带有 fetch 的 Mern 堆栈发布请求不起作用
【发布时间】:2021-03-06 04:02:22
【问题描述】:

我正在处理的 MERN 堆栈出现此错误 尝试发送发布请求以在 MongoDB 中创建新用户时。我收到此错误。我不确定为什么会发生这种情况,至少可以说令人沮丧。我只写了大约 6 个月的代码

  TypeError: Object(...) is not a function
  handleSubmit
  src/components/auth/RegistrationForm.js:27
  24 |   email: {email},
  25 |   password: {password}
  26 | }
   > 27 | create(user).then((response) => {
    | ^  28 |   if (response.error) {
    29 |     console.log(response)
    30 |   }

这是报名表

import React, { Fragment, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { toast } from 'react-toastify';
import { Button, CustomInput, Form, FormGroup, Input, Label } from 'reactstrap';
import Divider from '../common/Divider';
import SocialAuthButtons from './SocialAuthButtons';
import withRedirect from '../../hoc/withRedirect';
import axios from 'axios'
import create from '../../user/api-user';
const RegistrationForm = ({ setRedirect, setRedirectUrl, layout, hasLabel }) => {
  // State
  
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isAccepted, setIsAccepted] = useState(false);
  const [isDisabled, setIsDisabled] = useState(true);

  // Handler
   const handleSubmit = e => {
    e.preventDefault()
    const user = {
      email: {email},
      password: {password}
    }
    create(user).then((response) => {
      if (response.error) {
        console.log(response)
      }
    })
      

    toast.success(`Successfully registered as ${email}`);
    setRedirect(true);
  };

  useEffect(() => {
    setRedirectUrl(`/authentication/${layout}/login`);
  }, [setRedirectUrl, layout]); // the array are dependencies that trigger the function setREdirectUrl. good to know

  useEffect(() => {
    setIsDisabled( !email || !password || !confirmPassword || !isAccepted || password !== confirmPassword);
  }, [ email, password, confirmPassword, isAccepted]);

  return ( 
  <>
    <Form onSubmit={handleSubmit}>
      
      <FormGroup>
        {hasLabel && <Label>Email address</Label>}
        <Input
          placeholder={!hasLabel ? 'Email address' : ''}
          value={email}
          onChange={({ target }) => setEmail(target.value)}
          type="email"
        />
      </FormGroup>
      <div className="form-row">
        <FormGroup className="col-6">
          {hasLabel && <Label>Password</Label>}
          <Input
            placeholder={!hasLabel ? 'Password' : ''}
            value={password}
            onChange={({ target }) => setPassword(target.value)}
            type="password"
          />
        </FormGroup>
        <FormGroup className="col-6">
          {hasLabel && <Label>Confirm Password</Label>}
          <Input
            placeholder={!hasLabel ? 'Confirm Password' : ''}
            value={confirmPassword}
            onChange={({ target }) => setConfirmPassword(target.value)}
            type="password"
          />
        </FormGroup>
      </div>

      <CustomInput
        id="customCheckTerms"
        label={
          <Fragment>
            I accept the <Link to="#!">terms</Link> and <Link to="#!">privacy policy</Link>
          </Fragment>
        }
        checked={isAccepted}
        onChange={({ target }) => setIsAccepted(target.checked)}
        type="checkbox"
      />
      <FormGroup>
        <Button color="primary" block className="mt-3" disabled={isDisabled}>
          Register
        </Button>
      </FormGroup>
      <Divider className="mt-4">or register with</Divider>     
    </Form>
    <div>
      <Form>
    <SocialAuthButtons /> 
    </Form>
    </div>
  </>
 
    
  );
};

RegistrationForm.propTypes = {
  setRedirect: PropTypes.func.isRequired,
  setRedirectUrl: PropTypes.func.isRequired,
  layout: PropTypes.string,
  hasLabel: PropTypes.bool
};

RegistrationForm.defaultProps = {
  layout: 'basic',
  hasLabel: false
};

export default withRedirect(RegistrationForm);

这里是 api-user.js

import React from 'react'


const create = async (user) => {
    try {
        let response = await fetch('/api/user/', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(user)
        })
        return await response.json()
    } catch(err) {
        console.log(err)
    }
}

export default { create }

【问题讨论】:

标签: node.js reactjs mongodb express


【解决方案1】:

您将在Object 中导出创建方法。所以,你根本不能像这样调用函数。

解决办法是:

import { create } from '../../user/api-user';

或者,您可以这样做:

import UserApi from '../../user/api-user';

UserApi.create(user).then(...).catch(...);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2020-04-05
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2015-11-10
    • 2021-04-04
    相关资源
    最近更新 更多