最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Post request in react - Stack Overflow

programmeradmin5浏览0评论

Unable to send POST request by using fetch method

I am able to fetch request from the server but unable to Post the request dynamically. I am taking input value but it showing the error below:

Error: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

const url = "http://some domain/api/tweets";
const input = {tweet: {body:  ''}};
 
class App extends Component{
  constructor(props){
    super(props);
    this.state={
      error:null,
      isLoaded:false,
      data: [],
      value: ''
      
       
      
    }
    this.onSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  
 handleChange(e){
   this.setState({value: e.target.value});
 }

  ponentDidMount() {
    fetch("http://some domain/api/tweets")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            data: result.data
          });
        },
        
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

 handleSubmit(e){
  e.preventDefault()
  fetch(url, {
    method: 'POST',  
    body: JSON.stringify(this.state.value),  
    headers:{
      'Content-Type': 'application/json'
    }
  }).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
  }
  render(){
    const { error, isLoaded, data } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="list-type5">
       <form onSubmit={this.onSubmit} >
        <input type="text" placeholder="Body" value={this.state.value} onChange={this.handleChange}/>
        
        <input type="submit"  />
      </form>
        <ol>
          {data.map(i => (
            <div key={i.id}>
            <li >
           <a> <b> ID:</b>  {i.id} | <b> Body:</b> {i.body} | <b> Views:</b> {i.views}   </a>
            </li>
         
          </div>
             
          ))}
        </ol>
        </div>
      );
    }
  }
}
export default App;

Unable to send POST request by using fetch method

I am able to fetch request from the server but unable to Post the request dynamically. I am taking input value but it showing the error below:

Error: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

const url = "http://some domain/api/tweets";
const input = {tweet: {body:  ''}};
 
class App extends Component{
  constructor(props){
    super(props);
    this.state={
      error:null,
      isLoaded:false,
      data: [],
      value: ''
      
       
      
    }
    this.onSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  
 handleChange(e){
   this.setState({value: e.target.value});
 }

  ponentDidMount() {
    fetch("http://some domain/api/tweets")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            data: result.data
          });
        },
        
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

 handleSubmit(e){
  e.preventDefault()
  fetch(url, {
    method: 'POST',  
    body: JSON.stringify(this.state.value),  
    headers:{
      'Content-Type': 'application/json'
    }
  }).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
  }
  render(){
    const { error, isLoaded, data } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="list-type5">
       <form onSubmit={this.onSubmit} >
        <input type="text" placeholder="Body" value={this.state.value} onChange={this.handleChange}/>
        
        <input type="submit"  />
      </form>
        <ol>
          {data.map(i => (
            <div key={i.id}>
            <li >
           <a> <b> ID:</b>  {i.id} | <b> Body:</b> {i.body} | <b> Views:</b> {i.views}   </a>
            </li>
         
          </div>
             
          ))}
        </ol>
        </div>
      );
    }
  }
}
export default App;

Help would be appreciated.

Share Improve this question asked Aug 28, 2018 at 11:58 DafyDafy 1831 gold badge5 silver badges18 bronze badges 5
  • Can you console.log(this.state.value) and tell us what it is? – Arup Rakshit Commented Aug 28, 2018 at 12:03
  • On success callback, it should be JSON.parse(response) instead JSON.stringify(response)? – Arup Rakshit Commented Aug 28, 2018 at 12:07
  • yup this shows it takes input value – Dafy Commented Aug 28, 2018 at 12:09
  • Error is in client or server? I don't see JSON.parse in your code . – Arup Rakshit Commented Aug 28, 2018 at 12:09
  • Error is in client side and i just have written JSON.parse but it doesn't work @ArupRakshit – Dafy Commented Aug 28, 2018 at 12:13
Add a ment  | 

2 Answers 2

Reset to default 3

I just changed and remove const input = {tweet: {body: ''}}; from top and write it into the handleSubmit function just check it below:-

handleSubmit(e){
 e.preventDefault()
 const input = {tweet: {body:  this.state.value}};
 fetch(url, {
method: 'POST',  
body: JSON.stringify(input),  
headers:{
  'Content-Type': 'application/json'
 }
  }).then(res => res.json())
  .then(response => console.log('Success:', JSON.stringify(response)))
  .catch(error => console.error('Error:', error));
 }
handleSubmit(e) {
  fetch("http://some domain/api/tweets", { /*your object...*/ })
     .then(res => res.text()) // previous .then(res => res.json())
     .then(text => console.log(text))
     ...
}

The res.json() call seems to be wrong at this place, as your response might not be a valid JSON object. Maybe try res.text() instead and console.log your response to see what it tells you.

More infos about the response object you can find over here: MDN - Response Object

发布评论

评论列表(0)

  1. 暂无评论