[英]How to send a POST request in react to node.js Express?
I followed this video to get rid of cors issue.我跟着这个视频摆脱了cors问题。 It worked fine for GET request.But when I'm trying to send a POST request it is not working.
它适用于 GET 请求。但是当我尝试发送 POST 请求时它不起作用。 I don't have control at 3rd_Party_Api, so can't change anything of it.
我无法控制 3rd_Party_Api,因此无法更改任何内容。 My calls are as follows : req-request and res-response.
我的调用如下:req-request 和 res-response。
ReactApp(3000) --req--> Express(8080) --req--> 3rd_Party_API(9091)
ReactApp(3000) --req--> Express(8080) --req--> 3rd_Party_API(9091)
ReactApp <--res-- Express <--res-- 3rd_Party_API
ReactApp <--res-- Express <--res-- 3rd_Party_API
I'm not sure where I'm going wrong.我不确定我哪里出错了。 I'm posting my files here.
我在这里发布我的文件。 PostApp.js
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服务器.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);
})
}
Your server is using app.get
.您的服务器正在使用
app.get
。 To handle a post request you need to change it to app.post
or app.all
要处理发布请求,您需要将其更改为
app.post
或app.all
https://expressjs.com/en/guide/routing.html https://expressjs.com/en/guide/routing.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.