Reputation: 61
I followed this video to get rid of cors issue. It worked fine for GET request.But when I'm trying to send a POST request it is not working. I don't have control at 3rd_Party_Api, so can't change anything of it. My calls are as follows : req-request and res-response.
ReactApp(3000) --req--> Express(8080) --req--> 3rd_Party_API(9091)
ReactApp <--res-- Express <--res-- 3rd_Party_API
I'm not sure where I'm going wrong. I'm posting my files here. PostApp.js
import React, { Component } from 'react';
//import ReactDOM from 'react-dom';
import './App.css';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
varName: '',
submit: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({
varName: event.target.value
});
}
handleSubmit(event){
event.preventDefault()
const base_url="http://127.0.0.1:8080/api/addvar"
const data={varName:this.state.varName}
axios.post(base_url,data)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error.response)
})
console.log(JSON.stringify(data))
this.setState({
submit: this.state.varName
})
}
render(){
return(
<div className="App">
<form onSubmit={this.handleSubmit}>
<label>varName: </label>
<input type="text" value={this.state.varName} onChange={this.handleChange} />
<br/><br/><input type="submit" value="Add Name"/>
</form>
<h1>{this.state.submit}</h1>
</div>
)
}
}
export default App;
Server.js
var request = require('request-promise');
var cors = require('cors');
var express = require('express');
var url = require('url');
var bodyParser = require('body-parser');
var app = express();
var server = app.listen('8080',function(){console.log('listening to port 8080');});
app.use(bodyParser.json());
app.use(cors());
//app.get('/api/getNames',runThisCode);
console.log('got1');
app.get('/api/addName',plusname);
console.log('got3');
function plusname(req,res){
var input = req.body;
console.log('urlbody:' ,input);
var options = {
method: 'POST',
url: 'http://localhost:9091/v1/names/',
body: req.body,
header:{
'content-type' : 'application/json'
},
resolveWithFullResponse: true,
json: true
};
request(options)
.then((r1) =>{
res.send(JSON.parse(r1.body));
})
.catch(err =>{
console.log(err.response);
})
}
Upvotes: 1
Views: 8113
Reputation:
Your server is using app.get
. To handle a post request you need to change it to app.post
or app.all
https://expressjs.com/en/guide/routing.html
Upvotes: 1