React Native - 无法在前端导入猫鼬(但它可以从后端运行)

2024-03-12

我无法在前端导入猫鼬,但它在后端有效。

我有一个单独的后端目录。我有一些代码可以将几个用户添加到我的数据库中。这里是.....

import mongoose from 'mongoose';
import User from './models/user';

const users = [
  {
    id: 1,
    username: 'Matthew',
    password: 'Smith',
  },
  {
    id: 2,
    username: 'Deborah',
    password: 'Smith',
  },

];

// Connect to MongoDB
mongoose.connect('mongodb://localhost/users');

// Go through each movie
users.map(data => {
  // Initialize a model with movie data
  const user = new User(data);
  // and save it into the database
  user.save();
});

上面的代码有效。

现在我希望我的登录屏幕接受用户名和密码并将其发送到数据库。我陷入困境,因为我什至无法导入猫鼬(你会在下面看到我将其注释掉)。

我得到的错误是: 'TransformError: [我的项目的目录路径]/node_modules/mongoose/lib/drivers/index.js: require() 必须有一个字符串文字参数:[我的项目的目录路径]/mongoose/lib/drivers/index.js: js:7'

登录屏幕代码:

import React from 'react';
import { StyleSheet, Text, View,Navigator,TextInput, KeyboardAvoidingView,TouchableOpacity,
AsyncStorage,
 } from 'react-native';


//import mongoose from 'mongoose';



import {
  StackNavigator,
} from 'react-navigation';



export default class Login extends React.Component {


    //check to see if user has logged in already
    componentDidMount(){
        this._loadInitialState().done();
    }

    //get info from async storage
    _loadInitialState = async () => {
        var value = await  AsyncStorage.getItem('user');

        if(value != null){   //if the user is already logged in
            this.props.navigation.navigate('Profile');      //**profile page that we will create later
        }
    }

    constructor(props){
        super(props);
        this.state = {
            username: '',
            password: '',
        }
    }

  render() {
    return (
      //<View style={styles.container}>

        <KeyboardAvoidingView behavior = 'padding' style = {styles.wrapper}>
            <View style = {styles.container}>
                <Text style={styles.header}> - LOGIN - </Text>
                <TextInput
                    style={styles.textInput} placeholder='Username'
                    onChangeText={(username) => this.setState({username})}
                />
                <TextInput
                    style={styles.textInput} placeholder='Password'
                    onChangeText={(password) => this.setState({password})}
                />
            </View>


            <TouchableOpacity
                style={styles.btn}
                onPress = {this.login}>
                <Text>Log in</Text>
            </TouchableOpacity>

        </KeyboardAvoidingView>


     // </View>
    );
  }

  login = () => {
      alert('test');

      //send to server
      fetch('http://1.1.1.1/3000/users', {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
          },
          body: JSON.stringify({
              username: this.state.username,
              password: this.state.password,
          })
      })

      //handle response
      .then((response) => response.json())
      .then((res) => {

            //if user and pass exists, then log them in
            // res: result
            if(res.sucess === true){
                AysncStorage.setItem('user',res.user);
                this.props.navigation.navigate('Profile'); //navigate user to profile page
            }
            //else, tell the user they dont exist in the database
            else{
                alert(res.message);
            }
      })
      .done();
  }

}


const styles = StyleSheet.create({

    wrapper: {
      flex: 1,
    },

  container: {
    flex: 1,
    backgroundColor: '#2896d3',
    alignItems: 'center',
    justifyContent: 'center',
    paddingLeft: 40,
    paddingRight: 40,
  },

  header: {
    fontSize: 24,
    marginBottom: 60,
    color: '#fff',
    justifyContent: 'center',
    paddingLeft: 40,
    paddingRight: 40,
  },

  textInput: {
    alignSelf: 'stretch',
    paddingLeft: 16,
    marginBottom: 20,
    backgroundColor: '#fff',
  },

  btn: {
      alignSelf: 'stretch',
      padding: 20,
      marginBottom: 20,
      backgroundColor: '#01c853',
      alignItems: 'center',
  },
});

为什么我无法导入它?


Mongoose 的浏览器库 http://mongoosejs.com/docs/browser.html不支持mongoose.connect()。它仅支持模式和文档验证,目前无法实际连接到 MongoDB 或保存文档。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Native - 无法在前端导入猫鼬(但它可以从后端运行) 的相关文章

随机推荐