Trying to fetch API I created to react component - reactjs

So I created test API and added few test records to the DB.
Now when I wanted to fetch the data in react component I'm getting this error
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
when I try to console.log the data to see if it works. I asume it has something to do with the fact, that I run the API server on port 8080 and react app on 3000 (when I switched api to 3000 and clicked "back arrow" I saw a console.log with the data, but when I refreshed the site it realised the API is "occupying" this URL now).
How can I fix that? Here is the important part of the code, if I need to post more please do let me know.
API (app\src\apiTest\index.js):
const express = require('express');
const routes = require('./api.js');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
//connect to mongodb
mongoose.connect('mongodb://localhost/drugDB');
mongoose.Promise = global.Promise;
//serving files (folder name)
app.use(express.static('../../../src'));
app.use(bodyParser.json());
//initialize routes
app.use('/api', routes);
//error handling middleware
app.use(function(err, req, res, next){
res.send({error: err.message})
})
app.listen(process.env.port || 8080, function(){
console.log('listening')
})
2nd file in API
const express = require('express');
const Drug = require('./models/drug');
const router = express.Router();
//get list of drugs
router.get('/leki', function (req, res) {
Drug.find({}).then(function(drugs){
res.send(drugs);
})
})
router.post('/leki', function (req, res, next) {
Drug.create(req.body).then(function (drug) {
res.send(drug);
}).catch(next);
})
router.put('/leki/:id', function (req, res, next) {
Drug.findByIdAndUpdate({ _id: req.params.id }, req.body).then(function () {
Drug.findOne({ _id: req.params.id }).then(function (drug) {
res.send(drug);
})
})
})
router.delete('/leki/:id', function (req, res, next) {
Drug.findByIdAndRemove({ _id: req.params.id }).then(function (drug) {
res.send({ type: drug })
});
})
module.exports = router;
react component (app\src\components\MainPanel\panel.js):
componentDidMount(){
fetch('/api/leki').then(function(data){
console.log(data.json());
})
}

The error is suggesting that you're not receiving JSON back in response. Which is the case because inside of your leki endpoint you're using res.send(drug); which sends data back as HTML, change it to res.json({data: drug}) and then inside of componentDidMount:
componentDidMount(){
fetch('/api/leki', {
method: 'GET',
headers: {
'Accept': 'application/json',
}
}).then(function(response){
return response.json();
}).then(function(data) {
console.log(data.drug)
})
}

Try this:
componentDidMount() {
fetch('/api/leki')
.then(function (resolve) { return resolve.json(); })
.then(function (resolveJson) {
console.log(resolveJson);
});
}
Look at this for more information:
https://developers.google.com/web/updates/2015/03/introduction-to-fetch

You need to allow Cross Origin requests by setting a header in your response in the backend.
Place this code where you send your response:
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');

Related

Express Route is not working and always return status 200 response

I am trying to create POST api route ("/upload") but then the route isn't working correctly. I think the cause might be from
app.use((req, res, next) => { res.sendFile(path.join(__dirname, "..", "build", "index.html")); });
which I followed from a blog when setting up react and express server. I tried testing with Postman and it always get 200 response. Please help!!
server.js (Express)
const path = require("path");
const express = require("express");
const app = express(); // create express app
const fileUpload = require('express-fileUpload');
// add middleware
app.use(express.static(path.join(__dirname, "..", "build")));
app.use(express.static("public"));
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "..", "build", "index.html"));
});
app.use(fileUpload());
app.post('/upload', (req, res) => {
if (req.files === null) {
return res.status(400).json({ msg: 'No file uploaded' });
}
const file = req.files.file;
file.mv(`${__dirname}/public/uploads/${file.name}`, err => {
if (err) {
console.error(err);
return res.status(500).send(err);
}
res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
});
});
// start express server on port 5000
app.listen(5000, () => {
console.log("server started on port 5000");
});
index.js (React)
const handleUpload = async e => {
e.preventDefault();
const formData = new FormData();
formData.append('file', file);
try {
console.log(file)
const res = await axios.post('/uploads', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
const { fileName, filePath } = res.data;
console.log(fileName);
console.log(filePath);
} catch (err) {
if (err.response.status === 500) {
console.log('There was a problem with the server');
} else {
console.log(err.response.data.msg);
}
}
};
POST Result (Postman)
enter image description here
I want to create a POST api route ("/upload") so that I can save the uploaded file from the <input type=file/> in a specific folder. Currently, the API response always getting 200 status but I feel like it actually isn't connecting with the server side routing.

Axios React cors issue on product

my third party axios requests works properly on local mode properly thanks to "http-proxy-middleware", but after i build and deploy it, axios requests gives homepage html as response.
setupProxy.js file
const { createProxyMiddleware } = require("http-proxy-middleware")
const cors=require("cors")
const express = require('express');
const app = express();
module.exports=app=>{
app.use(
createProxyMiddleware("/api",
{
target:"third-party-api-url",
secure:false,
changeOrigin:true
})
)
ApiFrontend.jsx file
const [apiData,setApiData]=useState("")
var data = JSON.stringify({
"MERCHANT": "****",
"MERCHANT_KEY": "*******************************"
});
var config = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data : data
};
useEffect(()=>{
axios("/api",config)
.then(function (response) {
setApiData(response.data);
})
.catch(function (error) {
console.log(error);
});
},[])
i tried node server with express and use;
app.use(cors({
origin: API_URL,
credentials: true
}));
but it gives the same response

Send data react axios

Send data React to Node
If send data with axios.
is it correct?
react:
let data = {pp: number};
axios.post('http://localhost:3001/number', {
body: data
}). then((response) => {
console.log('data submitted success');
}).catch((error) => {
console.log('got err', error);
});
this in server
router.post('/', function (req, res) {
var countValue = req.body;
console.log('CountValue is', countValue);
});
It seems you need to put bodyParser.json() in your middleware.
For example:
app.use(bodyParser.json());
After that, you could use below code as your HTTP response in the controller.
res.status(200).json({ results: countValue });
I believe you don't need to use JSON.stringify(countValue)
Feel free to share more details for us :)

React-native: Problem sending log - console.error

I'm working with Expo React native, I'm trying to send POST request to my express server using axios
App.js - in my React
Axios({
url:'http://172.20.1.19:3001/api/tracking/locator',
method:'POST',
data:{
test:'wew'
},
config:'JSON',
headers:{
"Access-Control-Allow-Origin": "*"
}
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
In node status its 200, but when console.log the response it throws an error
console.error. "There was a problem sending log message to your
development environment",
Tracking.js - Express
var express = require('express');
var cors = require('cors');
var router = express.Router()
const app = express();
const db = require('../models');
app.use(cors({origin:'http://172.20.1.19:19001'}));
router.get('/', function(req, res, next){
res.json({
data: {
test :'wew'
}
})
})
router.post('/locator', function(req,res,next){
res.json({
data:{
status:'pano mo nasabe'
}
})
})
module.exports = router
Try to use:
(this helped me)
console.log(JSON.stringify(response.data))
or
console.log(response.data)
also
console.log(JSON.stringify(response))

Send http request in Ionic with Angular http

I have an ionic app that I am trying to send my Stripe token to, for payment processing. When I send the request to the node server with curl it is receiving the request. However, when I try to send the request via Angular's http module, it isn't registering at all. All of this is currently being tested locally, so that might be part of the issue?
HTML
<button (click)="testPost()" ion-button full>TEST POST</button>
cart.ts
...
import {Http, Headers, RequestOptions} from '#angular/http';
import { Stripe } from '#ionic-native/stripe';
#Component({
selector: 'page-cart',
templateUrl: 'cart.html',
})
export class Cart {
constructor(
...
private http: Http,
private stripe: Stripe
) {
//
});
}
testPost() {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
let postParams = {
body: {
token: 'axqrexample123tokenbasdflkjo3',
amount: 225
}
}
this.http.post("http://11.1.1.7:3100/charge", postParams, options)
.subscribe(data => {
console.log(data['_body']);
}, error => {
console.log(error);// Error getting the data
});
}
}
NODE SERVER
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var stripe = require("stripe")("sk_test_abcTAdefgn1oDexamplex");
app.use(bodyParser.json());
app.post('/charge', function (req, res) {
var token = req.body.token;
var amount = req.body.amount;
stripe.charges.create({
amount: amount,
currency: "usd",
source: token, // obtained with Stripe.js
description: "Charge for jones#example.com"
}, function(err, charge) {
// asynchronously called
});
res.send('Hello World!')
});
app.listen(3100, function () {
console.log('Example app listening on port 3100!')
})
I think you need to map the request before subscribing to the request
this.http.post("http://11.1.1.7:3100/charge", postParams, options)
.map(res => res.json())
.subscribe(data => {
console.log(data['_body']);
}, error => {
console.log(error);// Error getting the data
});
also, import the rxjs
import 'rxjs/Rx';
I would try this in the stripe.charges.create callback and see what happens:
}, function(err, charge) {
if (err) throw err;
console.log('Charge ID:', charge.id);
res.send('Hello World!');
});

Resources