简体   繁体   English

React 上的 axios POST 不适用于后端 MYSQL(但适用于邮递员)

[英]axios POST on React dosen't work with backend MYSQL (but works on postman)

So I test my routes o user on my backend with POSTAMN and everything works.所以我用 POSTAMN 在我的后端测试我的用户路由,一切正常。 But when I add axios on frontend to test the AXIOS POST, it sent me error server but all my values are okey.但是当我在前端添加 axios 来测试 AXIOS POST 时,它向我发送了错误服务器,但我的所有值都正常。 What I do wrong ?我做错了什么? If somebody can help me, thanks.如果有人可以帮助我,谢谢。

Here is the error I get这是我得到的错误

enter image description here在此处输入图像描述

so this is my form (formik) with axios request所以这是我的带有 axios 请求的表单(formik)

 import React from "react"; import {ErrorMessage, useField } from 'formik'; export const TextField = ({ label, ...props}) => { const [field, meta] = useField(props); return ( <div className="input-form"> <label htmlFor={field.name}>{label}</label> <input className={`form ${meta.touched && meta.error && 'is-invalid'}`} {...field} {...props} /> <ErrorMessage component="div" name={field.name} className="error"/> </div> ) }
 import React from "react"; import {Formik, Form} from 'formik'; import { TextField } from "./TextField"; import * as Yup from 'yup'; import axios from "axios"; export const Login = () => { const validate = Yup.object({ email: Yup.string() .email('Email is invalid') .required('Email is required'), password: Yup.string() //.min(6, 'Password must be at least 6 charaters') .required('Password is required'), }) return ( <Formik initialValues={{ email: '', password: '', }} validationSchema={validate} onSubmit={values => { axios({ method: "post", url: `http://localhost:3001/api/auth/login`, values, }).then(function (res) { console.log("envoie-avant erreur") console.log(res); console.log(res.values); console.log("values"); }).catch((err) => { console.log(err); console.log("error-value") console.log(values) console.log("lecture de values après refus") }); console.log(values) console.log("test-values") }} > { formik => ( <div className="size-column-form"> <h1>Login</h1> <Form> <TextField label="Email" name="email" type="email"/> <TextField label="password" name="password" type="password"/> <button className="btn-bleu" type="submit">Se Connecter</button> </Form> </div> )} </Formik> ) }

And this is my app.js with route and autorization CORS这是我的带有路由和自动化 CORS 的 app.js

 const express = require("express"); //crééer un application express const path = require("path"); const Sequelize = require("sequelize"); const app = express(); //variable d'environnement require("dotenv").config(); console.log(process.env); //const morgan = require("morgan"); //mysql importation connexion //app.use(morgan("dev")); //import des routes const authRoutes = require("./routes/user"); //intercepter toute requête d'un contenttype.json app.use(express.json()); const cors = require('cors'); const corsOptions ={ origin:'http://localhost:3000/', credentials:true, //access-control-allow-credentials:true optionSuccessStatus:200 } app.use(cors({credentials: true, origin: 'http://localhost:3000/'})); // middlewear general qui s'applique à toute les roots qui permet de gerer les CORS app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization", "x-access-token, Origin, Content-Type, Accept" ); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader( "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS" ); next(); }); //Gestion de la ressource images de façon statique app.use("/images", express.static(path.join(__dirname, "images"))); //routes app.use("/api/auth", authRoutes); // pour exporter l'application/constante pour acceder aux fichiers depuis notre server node module.exports = app;

I found the solution, so in my axios I had to add "data: values, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(values), })" So it give我找到了解决方案,所以在我的 axios 中我必须添加“数据:值,标题:{'Content-Type':'application/json'},正文:JSON.stringify(values),})”所以它给

 validationSchema={validate} onSubmit={values => { axios({ method: "post", url: `http://localhost:3001/api/auth/login`, data: values, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(values), }) .then((res) => { console.log(res); if (res.data.errors) { emailError.innerHTML = res.data.errors.values; } else { window.location = "/home"; } }) .catch((err) => { console.log(err); }); }}

And on my CORS BACKEND I made this:在我的 CORS BACKEND 上,我做了这个:

 const cors = require('cors'); const corsOptions ={ origin:'http://localhost:3000/', credentials:true, //access-control-allow-credentials:true optionSuccessStatus:200 } app.use(cors({credentials: true, origin: 'http://localhost:3000'})); // middlewear general qui s'applique à toute les roots qui permet de gerer les CORS app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', "*"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization'); res.header("Access-Control-Allow-Credentials", "true"); next(); });

So this is solve and I found this type of Axios with doc Axios : https://axios-http.com/docs/api_intro And when I saw that axios doesn't work I try with methode fetch: https://jasonwatmore.com/post/2020/02/01/react-fetch-http-post-request-examples所以这是解决了,我发现这种类型的 Axios 带有文档 Axios: https ://axios-http.com/docs/api_intro 当我看到 axios 不起作用时,我尝试使用 methode fetch: https://jasonwatmore。 com/post/2020/02/01/react-fetch-http-post-request-examples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Axios帖子在React Native上不起作用,但在PostMan上起作用 - Axios post not working on React Native but works on PostMan Axios 发布请求 React.js 时出现网络错误,但适用于 Postman - Axios Network error on post request React.js but works on Postman 通过Axios发送发布请求会在Spring-Boot后端生成一个空的RequestBody。 在Postman中工作,但不能通过Axios发布请求工作 - Sending a post request through Axios is generating an empty RequestBody in Spring-Boot backend. Works in Postman but not through Axios post request 反应 axios 然后工作但 catch 不起作用 - react axios then works but catch doesn't work POST请求适用于Postman,但不适用于axios或.fetch() - POST request works with Postman, but not with axios or .fetch() Mongoose .lt不使用post值 - Mongoose .lt dosen't work with post value Axios.post在React JS中不起作用 - Axios.post doen't work in react js 将作品放入 Postman 而不是 AXIOS - Put works in Postman but not AXIOS Axios 库无法响应 post 请求,尝试使用 curl 和 postman 工作 - Axios library failing to respond for post request, trying with curl and postman works 无法让我的 api 在 Postman 中工作,POST 返回 404。它是一个 vue 前端和 express 后端 - Can't get my api to work in Postman, POST returns 404 . its a vue frontend and express backend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM