0


I want to send data from ReactTS to API.
When trying with Postman, data gets posted without a problem.

API:

        [HttpPost]
        public async Task<ActionResult<Ticket>> PostTicket([FromBody]Ticket ticket)
        {
            _context.TicketList.Add(ticket);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetTicket", new { id = ticket.Id }, ticket);
        }

NOTE: When i change [FromBody] => [FromForm] the request passes with all the values being "null"

This is the code in ReactTS:

const TicketAdd = () => {
  const [ticketNameValue, setTicketName] = useState("");
  const [eventLocationValue, setEventLocation] = useState("");
  const [extraInfoValue, setExtraInfo] = useState("");
  const [eventDateValue, setEventDate] = useState("");
  const [formError, setFormError] = useState("");

  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTicketName(e.target.value);
  };

  const handleLocationChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEventLocation(e.target.value);
  };

  const handleInfoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setExtraInfo(e.target.value);
  };

  const handleDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEventDate(e.target.value);
  };

  const handleAddClick = () => {
    setFormError("");
    if (ticketNameValue !== "" && eventLocationValue !== "" && 
          extraInfoValue !== ""&& eventDateValue !== "") {
        const ticketObj = { 
                      ticketName:ticketNameValue, 
                      eventLocation:eventLocationValue, 
                      extraInfo:extraInfoValue, 
                      eventDate:eventDateValue};
        console.log(ticketObj);

        fetch('http://localhost:5000/api/tickets', 
        {method: 'POST', mode: 'no-cors', headers:{'Content-Type': 'application/json'},
         body: JSON.stringify({ticketObj}) })

    }
    else {
      setFormError("Insufficient data");
    }
  };

  return (
    <Form
      style={{
        margin: "10px 0px"
      }}
      onSubmit={e => e.preventDefault()}
    >
      <div>
          <Label>Ürituse nimi</Label>
          <Input
            type="text"
            value={ticketNameValue}
            onChange={handleNameChange}
            placeholder="Ürituse nimi"
          />
          <Label>Ürituse toimumiskoht</Label>
          <Input
            type="text"
            value={eventLocationValue}
            onChange={handleLocationChange}
            placeholder="Ürituse toimumiskoht"
          />
          <Label>Toimumiskuupäev</Label>
          <Input
            type="date"
            value={eventDateValue}
            onChange={handleDateChange}
            placeholder="Toimumiskuupäev"
          />
          <Label>Lisainfo</Label>
          <Input
            className="field"
            type="textarea"
            value={extraInfoValue}
            onChange={handleInfoChange}
            placeholder="Lisainfo"
          />
        {formError ? <p style={{ color: "red" }}>{formError}</p> : ""}
      </div>
      <Button color="primary" onClick={handleAddClick}>
        Lisa pilet
      </Button>

      <Link to='./tickets'>
        <Button color='primary' onClick={()=>{}}>
          Tagasi
        </Button>
      </Link>
    </Form>
  );
};

export default TicketAdd;

This is the error I get from browser:

enter image description here

Any thoughts? Thanks

keikai
  • 14,085
  • 9
  • 49
  • 68
TaaviM
  • 1
  • 3

1 Answers1

0

Maybe the real problem is api

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
         app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    }

try to add Usecors your startup.cs

  • Cannot pass ticketObj that way. It leads to error: Argument of type '{ method: string; mode: "no-cors"; headers: { 'Content-Type': string; }; body: { ticketName: string; eventLocation: string; extraInfo: string; eventDate: string; }; }' is not assignable to parameter of type 'RequestInit'. – TaaviM Mar 21 '20 at 20:42
  • sorry i read the document for "fetch" method.You are right! Did you try add Accept: 'application/json' to header – Hasan Dikengul Mar 21 '20 at 20:52
  • Did you try Configure your api? verify that your server is able to process the value defined in the Content-Type header – Hasan Dikengul Mar 21 '20 at 21:02
  • So, i added UseCors to startup, and removed mode='no-cors' from React...now POST succeeds, but all the values are NULL.... – TaaviM Mar 21 '20 at 21:18