我正在用 React Native 编写一个应用程序,并且创建了一个 MySQL 数据库来存储我的信息,但我想知道是否可以使用 axios 或 fetch 与我的数据库交互,因为它是本地的并且没有 HTTP 地址然而?
我觉得我以前能够做到这一点,但我忘记了要使用的语法...如果有人知道任何事情,我将不胜感激。
谢谢
React Native 和 Mysql 之间没有直接联系。所以需要使用Node.js。
Step 1:
npm install express
npm install body-parser
npm install mysql
Step 2:
const connection = mysql.createPool({
host : 'localhost', // Your connection adress (localhost).
user : 'root', // Your database's username.
password : '', // Your database's password.
database : 'my_db' // Your database's name.
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/users', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM users', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/users so you can see the data.');
});
获取 React Native 应用程序中的数据。您需要使用 PC 的 IP 地址。如果你使用localhost
您访问智能手机/模拟器本地主机。下面是一个需要遵循的示例:
getData(){
fetch('http://yourpcip:3000/users')
.then(response => response.json())
.then(users => console.log(users))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)