Node.js React Fetch()我的本地节点Express后端;无法返回后端测试值

Node.js React Fetch()我的本地节点Express后端;无法返回后端测试值,node.js,reactjs,azure,express,backend,Node.js,Reactjs,Azure,Express,Backend,我正在尝试使用节点设置后端服务器,但是,我无法从前端应用程序获取从后端发送的测试值。如果工作正常,我应该显示“测试从后端获取数据” 另外,我对HomeScreen.js中的fetch有点困惑,我应该放什么IP地址?我每次更换设备时都需要更新吗 如果我想连接到azure sql数据库,我应该在user.js中更改什么? 谢谢 这是我的app.js: var express = require('express'); var path = require('path'); var cookiePar

我正在尝试使用节点设置后端服务器,但是,我无法从前端应用程序获取从后端发送的测试值。如果工作正常,我应该显示“测试从后端获取数据”

另外,我对HomeScreen.js中的fetch有点困惑,我应该放什么IP地址?我每次更换设备时都需要更新吗

如果我想连接到azure sql数据库,我应该在user.js中更改什么? 谢谢

这是我的app.js:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mysql = require('mysql');

var indexRouter = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
  // next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
这是我的user.js

var router = express.Router();
var mysql = require('mysql');

var connection = mysql.createConnection({
  // host:'localhost',
  // user: 'root',
  // password: 'root',
  // database: 'users'
  authentication: {
    options: {
      userName: "username", // update me
      password: "password" // update me
    },
    type: "default"
  },
  server: "azure-server", // update me
  options: {
    database: "database", //update me
    encrypt: true 
  }
});

router.post('/', function(req, res, next) {
  res.send({message: 'testing to get data from backend'});
});

module.exports = router;
这是我的登录Homescreen.js

import * as React from 'react';
import { StyleSheet, Text, View, ScrollView, Image, Button, TextInput, Alert, AsyncStorage } from 'react-native';

export default class HomeScreen extends React.Component {

  constructor(props) {
    super(props);
    // this.login = this.login.bind(this);
    this.state = {
      username: '',
      password: '',
    }
  }
    // state = {
    //         username: 'Username',
    //         password: 'Password'
    //       }

    componentDidMount() {
      this._loadInitialState().done();
    }

    _loadInitialState = async () => {
      var value = await AsyncStorage.getItem('user');
      if (value !== null) {
        this.props.navigate('Menu');
      }
    }

    static navigationOptions = {
    title: 'Home',
    };

    login = () => {
      // alert(this.state.username);
      fetch("https://123.123.123.123: 3000/users", {
        method: "POST",
        headers: {
          'Accept': 'application/json',
          'Content-type': 'application/json',
        },
        body: JSON.stringify({
          username: this.state.username,
          password: this.state.password,
        })
      })
      .then((response) => response.json()) 
      .then((res) => {

        alert(res.message);
        if (res.success === true) {
          AsyncStorage.setItem('user', res.user);
          this.props.navigation.navigate('Menu');
        }
        else {
          alert(res.message);
        }

      })
      .done();
    }

    render() {
    return (
      <ScrollView style={{flex: 1}}>
        <View style={styles.container}>
          {/* <ImageBackground style = {styles.background} source={require('./img/bg.gif')}> */}
          <Text style={{ color: "black", fontSize: 30 }}>MEDIC DRAW</Text>

          <Image style = {styles.login_image} source={require('../../img/blankprofile.jpg')} resizeMode="contain"></Image>

          <TextInput
            style={styles.input}
            placeholder= {"username"}
            autoCorrect={false}
            clearButtonMode="always"
            ref= "username"
            onChangeText={(username) => this.setState({username})}
            value={this.state.username}
          />
          <TextInput
            style={styles.input}
            placeholder= {"password"}
            autoCorrect={false}
            clearButtonMode="always"
            ref= "password"
            onChangeText={(password) => this.setState({password})}
            value={this.state.password}
            secureTextEntry = {true}
          />
          <Button
              title="Login"
              onPress= {this.login.bind(this)} // {() =>this.props.navigation.navigate('CreateAccount')}
            />
          <Button
              title="Sign Up"
              onPress={() =>this.props.navigation.navigate('CreateAccount')}
          />

          {/* </ImageBackground> */}
        </View>
      </ScrollView>
      );
    }
  }

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 30,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  input: {
    height: 40,
    width: '60%',
    borderColor: 'gray',
    marginBottom: '2.5%',
    borderWidth: 1
  },

  login_image: {
    height: '20%',
    marginBottom: '2.5%',
  },

  // background: {
  //   width: '100%',
  //   height: '100%',
  //   justifyContent: "center",
  //   alignItems: "center",
  // }
});
import*as React from'React';
从“react native”导入{样式表、文本、视图、滚动视图、图像、按钮、文本输入、警报、异步存储};
导出默认类主屏幕扩展React.Component{
建造师(道具){
超级(道具);
//this.login=this.login.bind(this);
此.state={
用户名:“”,
密码:“”,
}
}
//状态={
//用户名:“用户名”,
//密码:“密码”
//       }
componentDidMount(){
这是。_loadInitialState().done();
}
_loadInitialState=async()=>{
var value=await AsyncStorage.getItem('user');
如果(值!==null){
这个.props.navigate('Menu');
}
}
静态导航选项={
标题:"家",,
};
登录=()=>{
//警报(this.state.username);
取回(“https://123.123.123.123: 3000/用户“{
方法:“张贴”,
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify({
用户名:this.state.username,
密码:this.state.password,
})
})
.then((response)=>response.json())
。然后((res)=>{
警报(res.message);
如果(res.success==true){
AsyncStorage.setItem('user',res.user);
this.props.navigation.navigate('Menu');
}
否则{
警报(res.message);
}
})
.完成();
}
render(){
返回(
{/*  */}
医生抽签
this.setState({username})}
值={this.state.username}
/>
this.setState({password})}
值={this.state.password}
secureTextEntry={true}
/>
this.props.navigation.navigate('CreateAccount')}
/>
this.props.navigation.navigate('CreateAccount')}
/>
{/*  */}
);
}
}
const styles=StyleSheet.create({
容器:{
弹性:1,
玛金托普:30,
背景颜色:“#fff”,
对齐项目:“居中”,
为内容辩护:“中心”,
},
输入:{
身高:40,
宽度:“60%”,
边框颜色:“灰色”,
保证金底部:“2.5%,
边框宽度:1
},
登录图片:{
身高:20%,
保证金底部:“2.5%,
},
//背景:{
//宽度:“100%”,
//高度:“100%”,
//辩护内容:“中心”,
//对齐项目:“中心”,
// }
});
问题
  • 你有入门脚本吗
  • 你的应用程序已在侦听端口
  • 你是如何创建你的WebApp的?从头开始?快速发电机?问题
    • 你有入门脚本吗
    • 你的应用程序已在侦听端口

    • 你是如何创建你的WebApp的?从头开始?快速发电机?如果您在前端使用CreateReact应用程序,您可能需要在包中添加一个代理。jsonHi,您能解释得更清楚一点吗?谢谢如果您在前端使用CreateReact应用程序,您可能需要在包中添加一个代理。jsonHi,您能解释得更清楚一点吗?谢谢