-
Mar 14th, 2024, 03:12 AM
#1
Thread Starter
Fanatic Member
React Native Login connect with sql server ?
I created a Login application that connects to the sql server using Visual Studio Code. The Login and SignUp application logs into the sql server to read the Table 'TABUSERNAME' and export it to the grid, but I get an error, my computer's sql server information:
user: 'sa'
pass: 'Coffee'
server:'MICROSOFT' or '192.168.1.100'
database: 'Cafe'
Can you please fix my code errors ?
File: App.js
Code:
//App.js
import React, { useState } from 'react';
import { StyleSheet, View, TextInput, Button, FlatList, Text } from 'react-native';
import SQLite from 'react-native-sqlite-storage';
//import axios from 'axios';
const App = () => {
// Kh?i t?o state ?? l?u tr? thông tin ng??i dùng
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [sqliteData, setSqliteData] = useState([]); // Thêm 'sqliteData' vào danh sách các state
// Hàm x? lý khi ng??i dùng nh?n nút Login
const handleLogin = async () => {
//console.log('login1');
try {
// K?t n?i ??n c? s? d? li?u
const db = SQLite.openDatabase(
{
name: 'Cafe.db',
location: 'default',
//createFromLocation: '~www/test.db',
},
() => {
console.log('Connected to the database.');
},
(error) => {
console.error('Failed to connect to the database.', error);
}
);
// Th?c hi?n truy v?n SQL ?? l?y d? li?u t? b?ng
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM TABUSERNAME',
[],
(_, result) => {
if (result.rows) {
const rows = result.rows.raw();
setSqliteData(rows); // L?u tr? d? li?u t? SQLite vào state 'sqliteData'
} else {
console.log('No rows returned from the query.');
}
},
error => {
console.error('Failed to execute query.', error);
}
);
});
// ?óng k?t n?i c? s? d? li?u khi không s? d?ng n?a
//return () => {
db.close();
console.log('Database connection closed.');
//};
} catch (error) {
console.error(error.message);
}
};
// Hàm x? lý khi ng??i dùng nh?n nút Signup
const handleSignup = async () => {
try {
//
} catch (error) {
console.error(error.message);
}
};
return (
<View style={styles.container}>
<View style={styles.list}>
{/* Hi?n th? d? li?u trong ô l??i */}
<FlatList
data={sqliteData}
renderItem={({ item }) => <Text>{JSON.stringify(item)}</Text>}
keyExtractor={(_, index) => index.toString()}
/>
</View>
<View style={styles.inputText}>
<View style={styles.text}>
<View style={styles.user}>
{/* H?p v?n b?n ?? ng??i dùng nh?p tên ng??i dùng */}
<TextInput placeholder="Username" onChangeText={setUsername} />
</View>
<View style={styles.pass}>
{/* H?p v?n b?n ?? ng??i dùng nh?p m?t kh?u */}
<TextInput placeholder="Password" onChangeText={setPassword} secureTextEntry={true} />
</View>
</View>
<View style={styles.button}>
<View style={styles.login}>
{/* Nút ?? th?c hi?n ch?c n?ng ??ng nh?p */}
<Button title="Login" onPress={handleLogin} />
</View>
<View style={styles.signup}>
{/* Nút ?? th?c hi?n ch?c n?ng ??ng ký */}
<Button title="Signup" onPress={handleSignup} />
</View>
</View>
</View>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex : 1,
backgroundColor : '#e7feff',
},
list: {
},
inputText : {
top: 340,
},
text : {
marginLeft : 30,
},
button : {
width : 360,
height : 150,
marginHorizontal : 20,
justifyContent : 'center',
},
login : {
},
signup : {
top : 20,
},
})
File: server.js
Code:
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');
const app = express();
const port = 3000;
app.use(bodyParser.json());
const config = {
user: 'sa',
password: 'Coffee',
server: 'MICROSOFT',
database: 'Cafe',
};
app.post('/login', async (req, res) => {
try {
await sql.connect(config);
const result = await sql.query(`SELECT * FROM TABUSERNAME WHERE USERNAME='${req.body.username}' AND PASSWORDS='${req.body.password}'`);
sql.close();
res.json(result.recordset);
} catch (error) {
res.status(500).send(error.message);
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
-
Mar 14th, 2024, 03:36 AM
#2
Hyperactive Member
Re: React Native Login connect with sql server ?
Maybe posting your question in a React forum will be more helpful to you, https://www.reddit.com/r/reactjs/ or perhaps https://dev.to/t/react
-
Mar 14th, 2024, 08:07 AM
#3
Re: React Native Login connect with sql server ?
Try removing the eels from your hovercraft... once you do that, rebuild.
-tg
PS and if you need help with the eels, there's a link in my sig block.
-
Mar 14th, 2024, 08:35 AM
#4
Re: React Native Login connect with sql server ?
You are not hitting the database from React, you're hitting it from your NodeJS server.
Your NodeJS code is concerning because there are several bad practices going on, but I don't see anything technically wrong with what you're doing. Maybe try adding additional return statuses to help narrow down the issue:
Code:
app.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
await sql.connect(dbConfig);
const query = `SELECT * FROM TABUSERNAME WHERE USERNAME = @username AND PASSWORDS = @password`;
const request = new sql.Request();
request.input('username', sql.VarChar, username);
request.input('password', sql.VarChar, password);
const result = await request.query(query);
if (result.recordset.length > 0) {
res.json({ success: true, message: 'Login successful' });
} else {
res.status(401).json({ success: false, message: 'Login failed' });
}
} catch (err) {
console.error('Database connection error', err);
res.status(500).json({ success: false, message: 'Internal server error' });
} finally {
sql.close();
}
});
-
Mar 14th, 2024, 09:03 AM
#5
Re: React Native Login connect with sql server ?
If the SQL server is a separate server from the front end app server, then I would first make sure that the app server can access SQL server on port 1433, initiated from the app server. That can be tested as easily as running "Telnet 192.168.1.100 1433" from a command line. If the screen goes completely black and you get just a blinking cursor in the upper-left corner of the screen, then you're connected. If after a few seconds you get a result of "Connecting to 192.168.1.100...Could not open a connection to the host, ..." then your app server can't communicate with the SQL instance on the SQL server, which then becomes a server/network configuration issue and not a code issue.
If Telnet isn't installed, you will need to install it as an optional Windows component.
Edit: Your code seems to indicate that communication should take place on port 3000. I edited my above post to reference that port rather than the standard SQL port of 1433.
Edit again: Unless port 3000 is the port that your app listens on, in which case you *should* be testing the connection to port 1433 on the SQL server.
Bottom line, outside of any and all app code, you need to ensure that the app server can connect to the SQL instance on the SQL server as a first step.
Last edited by OptionBase1; Mar 14th, 2024 at 09:37 AM.
-
Mar 14th, 2024, 09:27 AM
#6
Re: React Native Login connect with sql server ?
You know: I admit not having a single clue about JavaScript (or whatever language he uses),
but i'm trying to marry "app.js", which opens a SQLite-Database (locally?), with "server.js", which is apparanetly ms-sql-server....
Last edited by Zvoni; Tomorrow at 31:69 PM.
----------------------------------------------------------------------------------------
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------------------
People call me crazy because i'm jumping out of perfectly fine airplanes.
---------------------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad
-
Mar 14th, 2024, 09:50 AM
#7
Re: React Native Login connect with sql server ?
Originally Posted by Zvoni
You know: I admit not having a single clue about JavaScript (or whatever language he uses)
The language at the top of his post is ReactJS which is a JavaScript framework similar to Angular and Vue. It is purely a front-end language. The language at the bottom of his post is NodeJS which is a server-side language that uses the JavaScript syntax, it is similar to PHP/ASP.NET only with a different syntax (and other differences but they aren't important).
Originally Posted by Zvoni
but i'm trying to marry "app.js", which opens a SQLite-Database (locally?), with "server.js", which is apparanetly ms-sql-server....
That is a good point. You could open a SQLite database from the front-end but it looks like his intention is to do this from the back-end. If that's the case then the front-end code needs to be changed to make an AJAX request to the login endpoint.
-
Mar 14th, 2024, 09:59 PM
#8
Thread Starter
Fanatic Member
Re: React Native Login connect with sql server ?
Hi everyone!
I'm self-taught React Native so I don't know much about this language. I haven't found a forum website about React Native yet, so I'm posting here, hoping you guys who know about this language will help.
1. In your opinion, the React Native forum website is the best today ?
2. Hi dday9 !
I tried the code you sent and when running, I still get the same error as mine: ERROR Cannot convert null value to object, please see my attached image file.
3. Hi OptionBase1 !
The server is my computer, I wrote the cafe sales management software in language C#, the SQL Server server is running well with language C# on my computer, I have opened the port to run on the internet so you can Don't bother using the telnet command to check,...
4. Hi Zvoni!
In the above article, I forgot to give all you the error when running: ERROR Cannot convert null value to object
I guess the error occurs in this code but I'm not sure, I don't know how to debug it like language C#, I will learn a lot from you, I guess the error code:
Code:
if (result !== null) {
if (result.rows !== null) {
const rows = result.rows.raw();
setSqliteData(rows);
} else {
console.log('No rows returned from the query.');
}
Will receive your response soon.
Attachment 190771
Attachment 190772
Last edited by dong; Mar 14th, 2024 at 10:05 PM.
-
Mar 15th, 2024, 08:31 AM
#9
Re: React Native Login connect with sql server ?
1. In your opinion, the React Native forum website is the best today?
I'm not going to vouch for other forums, but keep in mind that VBForums really doesn't have much mobile or web activity.
2. Hi dday9 !
I tried the code you sent and when running, I still get the same error as mine: ERROR Cannot convert null value to object, please see my attached image file.
The attachments aren't working for me, could you copy/paste the line that is giving you the null reference error?
3. Hi OptionBase1 !
The server is my computer, I wrote the cafe sales management software in language C#, the SQL Server server is running well with language C# on my computer, I have opened the port to run on the internet so you can Don't bother using the telnet command to check,...
The two different pieces of code you gave us was React and NodeJS, nothing with C#.
-
Mar 17th, 2024, 10:22 PM
#10
Thread Starter
Fanatic Member
Re: React Native Login connect with sql server ?
Hi dday9 !
1. You wrote: "The attachments aren't working for me, could you copy/paste the line that is giving you the null reference error ?" Did you install: npm install react-native-sqlite-storage --save ? Or you can create a new app and copy my 2 files App.js and server.js, can you follow my instructions ?
- I want to copy the line that's giving you the error, but I don't know how to debug step by step React and NodeJS. Can you show me how to debug it ? When it's running, I enter user and password and press the login button, I get an error: ERROR Cannot convert null value to object
2. You wrote: "The two different pieces of code you gave us was React and NodeJS, nothing with C#" I understand this problem, I mean my cafe sales management software is working well, now I want to write more about ordering food via phone: android, ios... instead of using a computer, but I'm learning React and NodeJS, I know C# but I don't know much about this language.
Last edited by dong; Mar 17th, 2024 at 10:58 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|