React Native-无法在前端导入猫鼬(但可从后端使用) [英] React Native - can't import mongoose on the front end(but it works from the backend)

查看:83
本文介绍了React Native-无法在前端导入猫鼬(但可从后端使用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能在前端导入猫鼬,但是在后端可以工作.

I cant import mongoose on the frontend but it worked on the backend.

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

I have a separate directory for the backend. I have some code to add a couple users to my database. Here it is.....

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();
});

上面的代码有效.

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

Now I want my login screen to accept the username and password and send it to the database. I'm stuck because I cant even import mongoose(you'll see below that I commented it out).

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

The error I get is: 'TransformError: [directory path of my project]/node_modules/mongoose/lib/drivers/index.js: require() must have a single string literal argument: [directory path of my project]/mongoose/lib/drivers/index.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.connect().它仅支持架构和文档验证,实际上无法连接到MongoDB或当前保存文档.

Mongoose's browser library doesn't support mongoose.connect(). It only supports schemas and document validation, it can't actually connect to MongoDB or save documents currently.

这篇关于React Native-无法在前端导入猫鼬(但可从后端使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆