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))
Related
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.
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
I have created an express server in which I am implementing a graphQL request. The following block of code was taken from postman snippets of a successful request
const express = require("express"),
app = express(),
port = process.env.PORT || 4000,
cors = require("cors");
var axios = require('axios');
var data = JSON.stringify({
query: `mutation claimTask ($taskId: String!, $assignee: String) {
claimTask (taskId: $taskId, assignee: $assignee) {
id
name
taskDefinitionId
processName
creationTime
completionTime
assignee
variables {
id
name
value
previewValue
isValueTruncated
}
taskState
sortValues
isFirst
formKey
processDefinitionId
candidateGroups
}
}`,
variables: {"taskId":"22","assignee":"demo"}
});
var config = {
method: 'post',
url: 'http://[my_ip]/graphql',
headers: {
'Authorization': 'Bearer ey....',
'Content-Type': 'application/json',
'Cookie': 'TASKLIST-SESSION=..'
},
data : data
};
app.use(cors());
app.listen(port, () => console.log("Backend server live on " + port));
app.post("/api", (req, res) => {
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
res.send({ message: JSON.stringify(response.data) });
})
.catch(function (error) {
console.log(error);
res.send({ message: error });
});
})
Currently I am calling this request from a react app with a button like this:
Axios({
method: "POST",
url: "http://localhost:4000/api",
headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res.data.message);
});
For the next step I want to pass the variables from my react app instead of writing them directly as string to express. What is the right approach to achieve this?
I am using the express server to avoid cors related issues.
Any suggestions can be useful, thank you!
So you want to send an Axios POST from react. Something along those lines should work:
const handleSubmit = (e) => {
e.preventDefault();
const variables = {
taskId: ”22”,
userId: “demo”
};
axios.post("http://localhost:4000/api", variables).then((response) => {
console.log(response.status);
});
};
Inspired by https://blog.logrocket.com/understanding-axios-post-requests/
I have a problem with matching routes. I am runnning react app on port localhost:3000, and node/express server is running on port localhost:3001.
I am trying to create a club by firing this request on the frontend:
async addClub(club) {
try {
let postData = await fetch(`${this.backendUrl}/club`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({...club}),
});
this.backendUrl is correctly imported
Route on the backend file is:
router.post('/club', async (req, res) => {
try {
const body = req.body;
await new Club(body).save((err, club) => {
if (err) return console.log(err)
console.log('New club created');
res.status(200).send({ msg: 'Club created' });
});
} catch(err) {
res.status(400).json({
msg: 'Bad Request'
})
}
})
But for some reason frontend execution cannot find route specified on the backend.
I get an error: POST http://localhost:3001/club 404 (Not Found)
I have other routes through which I create other things and they work perfectly.
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');