【问题标题】:Axios request automatically set urlaxios请求自动设置url
【发布时间】:2021-12-31 08:46:14
【问题描述】:

我正在尝试实现一个功能,使用 Express.js 作为 api 服务器和客户端中的 React.js 上传图像。

在 api 服务器中,我定义了一个上传图片的路由,例如:

userRoute.js

module.exports = app => {
    const User = require("../controllers/userController")
    let router = require("express").Router()
    const authJWT = require("../middleware/authJWT")
    const upload = require("../utils/multer")
   
    // endpoint is http://localhost:8800/api/users/profilePicture
    router.post(
        "/profilePicture",
        upload.single("image"),
        authJWT,
        User.uploadProfilePicture
    )

   // some other routes

    app.use("/api/users", router)
}

在客户端,我使用axios来处理请求

agent.ts

// the axios instance with the api endpoint 
const axiosInstance = axios.create({
    baseURL: "http://localhost:8800/api",
})

// app user-related requests 
const AppUser = {
   // I use this to upload image to api server
    uploadProfilePicture: (image: Blob) => {
        const formData = new FormData()
        formData.append("image", image)
        return axios.post<Image>("profilePicture", formData, {
                headers: { "Content-type": "multipart/form-data" },
        })
    },

    // other requests ...
}

当我点击上传文件按钮,查看inspect控制台时,上传文件url为http://localhost:3001/profiles/profilePicture,不是服务器url,当然这个路由和我在服务器中定义的路由不一样APIhttp://localhost:8000/users/profilePicture。所以它返回 404 not found。

【问题讨论】:

  • 你必须使用axiosInstance.post
  • @Mani Opps!我忘了。谢谢提醒!!

标签: reactjs api express axios


【解决方案1】:

感谢@Mani 的提醒,在agent.ts 我将Axios 定义为不是 默认实例。但是在请求中,我使用它作为默认实例,所以它不起作用。

我变了

return axios.post<Image>("profilePicture", formData, {
                headers: { "Content-type": "multipart/form-data" },
 })

return axiosInstance.post<Image>("profilePicture", formData, {
                headers: { "Content-type": "multipart/form-data" },
       })

所以它又可以工作了。

【讨论】:

    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2020-02-29
    • 2020-07-08
    • 2021-06-02
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多