【问题标题】:cant post using axios in react [duplicate]无法在反应中使用axios发布[重复]
【发布时间】:2021-10-07 02:34:06
【问题描述】:
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

浏览器提供:“CORS 策略已阻止从源 'http://localhost:3000' 访问 'localhost:5000/add-to-diary' 处的 XMLHttpRequest:跨源请求仅支持协议方案:http、data、chrome-extension、edge、https、chrome-untrusted。"

但我可以通过邮递员发帖

【问题讨论】:

标签: reactjs mongodb express


【解决方案1】:

首先,您的网址需要一个协议,即:

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

其次,因为你要跨域,即一个站点在 localhost:3000,另一个在 localhost:5000,你会得到控制台中提到的 CORS 错误。服务器(在 :5000 端口上的服务器)需要使用 Access-Control-Allow-Origin 标头进行响应,其值为 localhost:3000*(不太安全)。

查看here 了解有关 CORS 的更多信息。

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 2018-10-27
    • 2021-06-09
    • 2020-04-13
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多