-2
import React, { useState } from 'react'
import axios from 'axios'

const Add = () => {
    
    const [title, setTitle] = useState('')
    const [description, setDescription] = useState('')
    const [date, setDate] = useState('')
    const url = 'localhost:5000/add-to-diary';

    const handleSubmit = async e => {
        e.preventDefault();
        const data = {
          title,
          description,
          date
        }
        axios.post(url, data)
       .then(res => console.log(res.data))
       .catch(err => console.log(err.data)) 
    }
    
    return (
    <div className="add-to-diary">
        <h1>ADD <span className='green-text'>DIARY</span></h1>
        <form onSubmit={handleSubmit} >
            <div className="form-container">
                <label htmlFor='title'>Title</label>
                <input type='text' className='form-control' value={title} onChange={e => setTitle(e.target.value)} name='title' />
                <br/>
            </div>
            <div className="form-container">
                <label htmlFor='description'>Description</label>
                <textarea className='form-control' value={description} onChange={e => setDescription(e.target.value)} name='description'></textarea>
                <br/>
            </div> 
            <div className="form-container">
                <label htmlFor='date'>Date</label>
                <input type='date' className='form-control' value={date} onChange={e => setDate(e.target.value)} name='date' />
                <br/>
            </div>
            <button type="submit">Post</button>
        </form>
    </div>
    )
}

export default Add

browser gives: "Access to XMLHttpRequest at 'localhost:5000/add-to-diary' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted."

but I can post via postman

k3sha7
  • 5
  • 1
  • 2
    Does this answer your question? [ReactJS: has been blocked by CORS policy: Response to preflight request doesn't pass access control check](https://stackoverflow.com/questions/57388243/reactjs-has-been-blocked-by-cors-policy-response-to-preflight-request-doesnt) – Majid M. Aug 01 '21 at 11:01

1 Answers1

0

First of all, you'll need a protocol on your URL, i.e:

const url = 'http://localhost:5000/add-to-diary';

Secondonly, because you're going cross-domain, ie one site is on localhost:3000, and the other is on localhost:5000, you'll get the CORS error mentioned in the console. The server, (the one on the :5000 port), will need to respond with an Access-Control-Allow-Origin header, with a value of localhost:3000, or * (less secure).

Take a look here for more info on CORS.

SteveEdson
  • 2,485
  • 2
  • 28
  • 46