React Native - FETCH Response is empty - API Status 500 - POST Call - react-native

signIn = () => {
//post data to express backend
fetch('http://10.0.2.2:3000/api/v1/auth', {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: `login=${this.state.login}&password=${this.state.password}`
})
.then((response) => response.json())
.then ((res => {
if(res.status === 200) {
AsyncStorage.setItem('user', this.state.login);
this.props.navigation.navigate('Authorized')
} else {
alert("Response:", res);
}
}))
.done();
}
The above is for React-Native. And below is the express backend:
router.post('/', function(req,res){
var login= req.body.login;
var password = req.body.password;
var sql = `SELECT * FROM users WHERE username = '${login}' OR number = '${login}' AND password = ${password}`
db.query(sql, function (err, rows, fields) {
if (err) {
res.status(500).send({error: 'Something went wrong!'})
} else {
if(rows.length > 0) {
if (rows[0].password == password) {
res.status(200).send({success: 'Login Successful'})
}
} else {
res.status(404).send({error: 'Email or Password does not match!'})
}
}
})
});
I think there is nothing getting into a response or maybe some other problem which I am unable to figure out the moment.

Related

API timeline - one entire week

I'm new to API and Twitter
I managed to retrieve the 'normal' 20 Tweets (Status)
Is there a way to retrieve a whole week at once?
Or do I have to write a code that permanently calls 20 Tweets and append each after the other?
You can get whole week of tweet by Get User's lookup Tweet V2 API
OR
Get timeline for user by V1.1 API
Tweet User's lookup V2
GET /2/users/{user id}/tweets
get tweet time line by V1.1 API
GET statuses/user_timeline
I will demo both with Mr. Tweet by Postman.
#1 Get access token in here
This token support both V2 and V1.1 API call.
#2 Get Tweets one week by v2
https://api.twitter.com/2/users/44196397/tweets?max_results=20&start_time=2023-01-18T00:00:01Z&end_time=2023-01-25T00:00:01Z
If you want to more detail information for each tweet.
Add attribute option in here by Adding query parameters(like a like count, create at and so on)
#3 Get timeline, 20 Tweets by v1.1
Timeline API Two methods in here
https://api.twitter.com/2/users/:id/timelines/reverse_chronological
OR
https://api.twitter.com/2/users/:id/tweets
Demo for get tweet with 2nd methods
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=elonmusk&count=20
Both API needs access token assignment
Both API can be programming by node.js or Python languages.
const axios = require('axios')
const API_KEY = '<your API Key>'
const API_KEY_SECRET = '<your API Secret>'
const getToken = async () => {
try {
const resp = await axios.post(
url = 'https://api.twitter.com/oauth2/token',
data = '',
config = {
params: {
'grant_type': 'client_credentials'
},
auth: {
username: API_KEY,
password: API_KEY_SECRET
}
}
);
return Promise.resolve(resp.data.access_token);
} catch (err) {
console.error(err)
return Promise.reject(err)
}
};
const getUserId = async (username, token) => {
try {
const resp = await axios.get(
url = `https://api.twitter.com/2/users/by/username/${username}`,
config = {
headers: {
'Accept-Encoding': 'application/json',
'Authorization': `Bearer ${token}`,
}
}
);
// { data: { id: '44196397', name: 'Elon Musk', username: 'elonmusk' } }
return Promise.resolve(resp.data.data.id)
} catch (err) {
return Promise.reject(err)
}
};
const getTweetTimeline = async (user_id, start_date, end_date, token) => {
try {
const tweets = [];
let index = 1
let next_token = 'start'
while (next_token != null) {
let url = `https://api.twitter.com/2/users/${user_id}/tweets?start_time=${start_date}&end_time=${end_date}&tweet.fields=created_at&max_results=20`
if (next_token != 'start') {
url = `https://api.twitter.com/2/users/${user_id}/tweets?start_time=${start_date}&end_time=${end_date}&tweet.fields=created_at&max_results=20&pagination_token=${next_token}`
}
const resp = await axios.get(
url = url,
config = {
headers: {
'Accept-Encoding': 'application/json',
'Authorization': `Bearer ${token}`,
}
}
);
for(const item of resp.data.data) {
tweets.push({
index : index,
created_at: item.created_at,
text: item.text,
id : item.id
})
index = index + 1
}
next_token = resp.data.meta.next_token
}
return Promise.resolve(tweets)
} catch (err) {
console.error(err)
return Promise.reject(err)
}
}
getToken()
.then(token => {
console.log(token);
getUserId('elonmusk', token)
.then(user_id => {
getTweetTimeline(user_id,'2023-02-05T00:00:00Z','2023-02-11T23:59:59Z', token)
.then(tweets => {
for(const tweet of tweets) {
console.log(tweet)
}
})
.catch(error => {
console.log(error.message);
});
})
.catch(error => {
console.log(error.message);
});
})
.catch(error => {
console.log(error.message);
});
Result
node get-tweet.js > result.json

react native make accessToken global

im using rn-secure-storage to save authState when using oauth2, then i have class AppHelper to control all network function like below:
import RNSecureStorage, { ACCESSIBLE } from 'rn-secure-storage'
export const accessToken = async() => {
await RNSecureStorage.get("authState").then((value) => {
console.log("authState", value);
return JSON.parse(value).accessToken
}).catch((err) => {
console.log("can not get authState", err);
});
};
export const getData = (url, tag = 'getData') => {
return fetch(url, {
method : 'GET',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization' : 'Bearer ' + accessToken
}
})
.then((response) => {
console.log(tag, 'Bearer ' + accessToken);
return response.text();
})
.then((json) => {
console.log(tag, json)
return json;
})
.catch((error) => {
handleError(err)
console.log(tag, error, url)
});
}
export const handleError = (error) => {
if (error.response.code == 401){
alert('Unauthorized')
}else{
console.log('network call failed', error)
}
}
im coding native before, so im not familiar with React native syntax. I just want to get access token to apply in network call, but my code show error:
_getMasterInfoApi Bearer function _callee() {
return _regenerator.default.async(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _regenerator.default.awrap(_rnSecureStorage.default.get("authState").then(function (value) {
console.log("authState", value);
return JSON.parse(value).accessToken;
}).catch(function (err) {
handleError(err);
}));
case 2:
case "end":
return _context.stop();
}
}
}, null, null, null, Promise);
}
Can anyone help? thanks in advance

no response after axios.post()

Hey I'm working on a Login system on my vue project and have the problem that there seems to be no response from the backend.
This is the backend function:
auth.post('/login', async function (req, res) {
const { email, password } = req.body;
console.log(req);
if(email !== "" && password !== "") {
const account = await User.findOne({ where: { email: email} });
if (account) {
if (await account.validPassword(password)) {
// Generate an access token
const accessToken = jwt.sign({ id: account.id }, SECRET);
const account_data =
{
'id': account.id,
'firstName': account.firstName,
'lastName': account.lastName,
'email': account.email,
'isAdmin': account.isAdmin
}
res.send({accessToken, account_data});
} else {
res.status(200).json("Username or password incorrect");
}
} else {
res.send('Username or password incorrect');
}
} else {
res.send('Username or password incorrect');
}
})
This is the method were I call the action
methods: {
async loginUser(){
let user = await this.$store.dispatch('loginUser', this.loginInfo);
if(user.error){
alert(user.error)
} else {
alert('Thank you for signing in, ' + user.firstName);
}
},
}
This is the action:
async loginUser({commit}, loginInfo){
console.log(loginInfo)
try{
let response = await axios({
method: 'POST',
url: 'http://localhost:4000/api/auth/login',
data: loginInfo,
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}});
let user = response.data;
console.log(user);
commit('SET_CURRENT_USER', user);
} catch (e){
alert(e);
return {e}
}
}
Neither the console.log in the try function or in the catch function is triggered.

How to passing result of http request inside async in ExpressJS?

I have below code
async send(user, data) {
const postData = {
'data': 'john',
'secret': 'secret'
};
const dataJson = JSON.stringify(postData);
const options = {
hostname: 'example.com',
path: '/send',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': dataJson.length
}
};
const req = https.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(dataJson);
req.end();
//---------------
let postResult = // HERE I WANT TO GET WHAT HTTP POST REQUESTED (e.g dataJson.body?)
//---------------
let result;
try {
result = await this.users.collection('users').updateOne(
{
_id: user
},
{
$set: {
// I WANT TO USE THAT HERE
data1 : postResult,
data2 : data2
}
},
{ maxTimeMS: consts.DB_MAX_TIME_USERS }
);
} catch (err) {
log.error('DB', 'UPDATEFAIL id=%s error=%s', user, err.message);
err.message = 'Database Error, failed to update user';
err.code = 'InternalDatabaseError';
throw err;
}
return { success: true };
}
How to get those data to outside variable?
I almost crazy about this, been searching on google and not found anything
I am using express and native-http to make http request, are there any native-curl maybe?
thank you very much for all the help
Your current code is using callback to retrieve result, so you can initiate data variable to outside callback function
let data = '';
const req = https.request(options, (res) => {
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
})
And also there are other easier way to make http request with nodejs. you can check axios that support Promise and async/await.
you can use syntax like this with axios
const response = await axios.get('/user?ID=12345');
way more easier.

Reading post data from react-native

I have this fetch() method that is sending data from my react-native app to a laravel method
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
//let res = await response.text();
if (response.status >= 200 && response.status < 300) {
console.log(response);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
I can receive the data using this method
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData);
//parse_str($postedValue, $output);
return response()->json([
'name' => $postedValue,
'route' => $postedValue
]);
}
and attempting to return the just posted data. The posted data looks like this
12:35:07 PM:
{"type":"default","status":200,"ok":true,"headers":{"map":{"connection":["Keep-Alive"],"content-length":["54"],"content-type":["application/json"],"set-cookie":["XSRF-TOKEN=eyJpdiI6IlF1NWlLOE9rVCtlUXNpYzBFSTV0c0E9PSIsInZhbHVlIjoiNWtGenprRmJOYTVsc2dQRjNrcmpxZXhWeFZRd1NZSzdiOWFKUUZTZmJJaEN6U0RnbW9uOVZ4bGUrV2ZMYUlIb0NQNHFrT1pCWXB0dnlwTjhPWm56ZWc9PSIsIm1hYyI6IjU3NDJkNWE5M2U4YmIwNTUwNzhkZTM4ZTRlNDc5OTZhNjczYWEyODU0OGNmN2ViNDdkYTM4YjdjY2U1ZWE1ZmYifQ%3D%3D;
expires=Fri, 09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/,
laravel_session=zqcMrXeuwwGpEsR8Jh2WakDg0cdqLod4QsfMnfcd; expires=Fri,
09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/;
HttpOnly"],"access-control-allow-methods":["GET, POST, PUT, DELETE,
OPTIONS"],"access-control-allow-origin":["*"],"cache-control":["no-cache,
private"],"server":["Apache/2.4.18
(Ubuntu)"],"keep-alive":["timeout=5, max=100"],"date":["Fri, 09 Jun
2017 09:35:07
GMT"]}},"url":"http://no-tld/androidLogin","_bodyInit":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}","_bodyText":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}"}
I now want to access the returned email from my native-react app.
console.log(response.email); returns null. How can i access the returned email value in react native?
Try below fetch call,
React-native log-android //Android
or react-native log-ios // IOS
use to see response data or error details
fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: 'chesterfield#gmail.com', password: '123456'})
}).then((response) => response.json())
.then((responseData) => {
console.log("responseData : " +responseData); // fetch response data
}).catch((error) => {
console.log("error : " +error); // error
});
I fixed it this way
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://198.74.51.225/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
let res = await response.text();
if (response.status >= 200 && response.status < 300) {
let userData = JSON.parse(res);
console.log(userData.email);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
Just to be sure of the post data returned, you can modify the posted data in the server side and return it using this function
//Android Login
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData,true);
$token = rand(400,7833);
return response()->json([
'email' => $token."_".$postedValue['email'],
'password' => $postedValue['password']
]);
}
For this to work, i had to also allow cors using this middleware
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
and i used it in my route like this
//Android
Route::group(['middleware' => ['cors']], function() {
Route::post('androidLogin', 'Auth\LoginController#androidLogin');
});
Hope that helps someone trying to post or get from a react-native app.