Now, I have some server error problem.
I request to the server from react client and then server can not response.
I find an error position in my project.It comes from sequelize Database.
exports.createMemeber = (req, res) => {
console.log(req.body);
const { email, password } = req.body;
***author.findByPK(email)***
.then(res => {
res.send(email);
res.end();
})
.catch(error => {
res.status(400).send('No Validate')
})}
The main error position is
author.findByPK...
In this part there will be error in console window.
JavaScript is a case-sensitive language and the Sequelize docs show the method as findByPk (note the lower-case k).
Ref: http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-findByPk
Try to change findByPK to findByPk
Related
I'm currently having an error on my code on retrieving MySQL data upon clicking a button.
Here is my 'route.js'.
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password!',
database: 'mydb'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/user', 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 user', 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/user so you can see the data.');
});
async function test(){
await fetch('http://mylocalpcIP:3000/user',{
method: 'POST', // Here you're saying that you want to make a POST request. Could be any method, like a GET, for example.
headers: '', // You can specify your requisition headers here. That line is optional.
body: { // Here's the fun part. Put your data here.
"name": this.state.name,
"age": this.state.age,
"phone_number": this.state.phone_number
}
})
.then(response => response.json())
.then(user => console.warn(user))
};
export {test};
Then, I've called test function as such:
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import {test} from "./db/routes.js";
const MyScreen = ( {navigation} ) => {
return (
<View style={styles.container2}>
<TouchableOpacity
style = {[styles.mid_box, styles.pbox]}
onPress={() =>{
test();
navigation.navigate("Dating_to_Profiles")
}}>
<View>
<Text style = {styles.textstyle}>1st Introduced Profile</Text>
</View>
</TouchableOpacity>
And I'm getting this scary message when I reload the emulated Android.
Well.. It's very likely that I've messed up somewhere since I don't know much about anything yet.
I'd appreciate a lot if someone can teach me how to retrieve data via POST method.
Thanks a lot in advance!
Express is a NodeJS framework and thus obviously not compatible with react-native.
If you wanted to create an API where your data that was queried from MYSQL is served as JSON so it can be fetched by your app, I recommend this tutorial for you.
I need to access my Data from my mysql Database using express, on my server the data is as a json, but when i try to access it i always get 'undefined' and my express server crash
the json i have on the server :
[{"idProjet":1,"nomProjet":"test","dateDebut":"2021-05-18T22:00:00.000Z","nomAuteur":"mathieu","prenomAuteur":"jean","organisme":"idmc"}]
fetching code :
let id = 'id :';
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/projets')
.then(response => {return response.json()})
.then((json => {console.log(json);setData(json);}))
.catch(error => console.error(error));
console.log(data);
}, []);
Route.js code :
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'agora'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/projets', 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 projet', 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/projets so you can see the data.');
});
The most common problem for this type of behavior is that you are using react-native on an android emulator. Android Emulator is using an IP-address different from localhost on windows machine. For more information, check here the official documentation.
So you can forward your port on the same port used by the android emulator (10.0.2.2) or you can change the port to 80 so you won't have any problem
You can go check this answer here
I'm new in React Native and I'm trying to integrate my app with mySQL database located inside my hosting provider (digitalocean.com).
I've managed to get the data through nodejs and express but it's actually getting the data where my problem is.
Here how it goes:
I created a routes.js and inserted the following:
Note: the following credentials are real but is for pure testing and i don't mind sharing.
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '134.122.22.176',
user: 'yannb_9',
password: 'yannb_9',
database: 'tiomanGrow'
});
// Starting our app.
const app = express();
connection.connect((err) => {
if (err) {
console.log('Connection error message: ' + err.message);
return;
}
console.log('Connected!')
// Creating a GET route that returns data from the 'users' table.
app.get('/', function (req, res) {
// Connecting to the database.
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM farmers', 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/farmers so you can see the data.');
});
Up until now everything's great! you can click on the http://localhost:3000/farmers and you'll see the data when you run the file.
Here's where I get stuck:
I was to display the data on my app and i have no idea how to possibly do that.
I did a few researches and saw a possible solution which didn't work. it actually gave me a "Network request failed"
import React from "react";
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
import { HeaderImg } from '../components/HeaderImg';
import { Button } from '../components/Button';
export default class DB extends React.Component {
state = {
email: "",
password: "",
errorMessage: null
};
fetchData = async() => {
fetch('http://134.122.22.176:3000/farmers')
.then(response => response.json())
.then(users => console.dir(users))
.catch(error=> console.log(error))
}
render() {
return (
<View style={styles.container}>
<HeaderImg />
<View style={styles.errorMessage}>
{this.state.errorMessage && (
<Text style={styles.error}>{this.state.errorMessage}</Text>
)}
</View>
<Button
onPress={this.fetchData}
/>
</View>
);
}
}
const styles = StyleSheet.create({
});
Any suggestions?
The hostname for your MySQL database in your routes.js file is shown as 134.122.22.176. That's the database ip address. You cannot fetch from this IP address. MySQL databases do not respond to standard HTTP requests; they are not web servers.
Your Express app is running on localhost: http://localhost:3000/farmers - I am guessing you can surf to that URL in a web browser and see data, for example. If that Express app is running on your development computer, then you just need to find out the IP address (xx.xx.xx.xx) for that computer on your LAN, and use that in your fetch.
Starting from Android 9, google has decided to remove http client library from bootclasspath.
With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default.
For brief overview of the changes, visit.
In order to connect with http client, you have to add this line in your AndroidManifest.xml file:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
After that you should be able to connect with HTTP clients with your android Pie device.
Apologies for asking what looks like a common question but I cannot seem to be able to achieve.
I would like to click 'a' tag and open a new page to show an article according to the id from MySQL Database. But I got 500.
Could anyone tell me what's the matter with my codding? Thank You.
Here is the 'a' tag
<article v-for='item in dataGroup'>
<a :href="'http://localhost:8090/articlePage.html?articlePage?id='+item.ID" :name='pageId' target="__blank">
<h4>{{item.title}}</h4>
<p>{{item.intro}}</p>
</a>
</article>
I use Vue-resource to send the 'get' request
const vm = new Vue({
el: '#app',
data: {
dataGroup: [],
},
methods: {
renderArticle(url) {
this.$http.get(url, {
}).then((res) => {
this.dataGroup = res.data;
}, (res) => {
alert(res.status)
})
},
},
created() {
this.renderArticle('/articlePage')
}
})
Here is my server code
module.exports = () => {
var router = express.Router();
router.get('/', (req, res) => {
db.query(`SELECT * FROM articles_table WHERE ID='${pageId.id}'`, (err, page) => {
if (err) {
console.error(err);
res.status(500).send('database error').end();
} else {
res.send(page);
}
})
})
You have not defined a server side route for articlePage
You're never actually sending pageId to the server, so therefore you can't utilize it in your query as the server doesn't know what that variable is, let alone how to access id off of it.
You do not have a catchall (*) route defined to return a 404 error code, so the server is (presumably) responding with a 500 server error because it doesn't know how to handle the request.
Edit
Your URL doesn't make sense to me, it should be something like:
https://localhost:8090/articlePage.html?articlePageId='+item.ID
Then on the server side you can access any variables in the query string off of the request, like below:
req.query.articlePageId
The req.query part is where the magic happens
I am using create-react-app.
When you go to localhost:3001/test - it does serve up the HTML. But all you see is an empty page because nothing in the id "root" is rendered.
This is the code I have in my server:
app.get('/test', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
})
and my HTML is close to this:
<body>
<div id="root"></div>
</body>
You have to set the location of the static files. For example if you use environment variable.
if(process.env.ENV === 'prod'){
app.use(express.static('client/build'));
const path = require('path');
app.get('/test', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
Also, do make sure to run npm run build in order to create all the necessary files for deployment.
Based on the few details provided, I'll give a checklist
1- Make sure you have root in this part of your code
ReactDOM.render(<YourApp />, document.getElementById('root'));
2- In your console, do you have any error messages similar to this?
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
...Then your are just simply not receiving your data from the server because of CORS issues. Use this: CORS
3- Double check that your server that does the res.sendFile is running properly, check your terminal to check for errors like "file not found" or similar issues.
4- This works (I just tried it), try it in the same directory as your current server. Paste the code in testNode.js and run node testNode.js then visit http://localhost:3003/test
const express = require('express')
const app = express()
const port = 3003
app.get('/test', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
})
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
5- Is the public/ folder readable? Does it have the right permissions? Try a chmod -R 777 public/ (change it back later)