小编sin*_*090的帖子

从 nextjs API 路由发送文件

我使用 nextjs API 路由连接到外部 API

当我使用POST请求发送文件时,该文件在 API 路由中未正确处理,我得到422 Unprocessable Entity Error

当我仅发送文本时没问题,但是当我添加文件时会发生此错误。

我的请求

const data = new FormData();
        data.append('first_name', firstName);
        data.append('last_name', lastName);
        data.append('phone_number', phoneNumber);
        image && data.append('avatar', image);

        axios.post(`${API_ROUTE}`, data, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(res=>{
            alert(JSON.stringify(res.data, null, 2));
        })
Run Code Online (Sandbox Code Playgroud)

我的 API 路线

    const config = {
        headers: {
            'Content-Type': req.headers['content-type']
        }
    };

    axios.post(address, req.body, config)
    .then(r=>{
        res.statusCode = 200
        res.json( r.data )
    })
    .catch(err=>{
        res.json(err)
    })
Run Code Online (Sandbox Code Playgroud)

在API Route发送到外部API的请求中,?文件内容中有一些,但是在从浏览器发送到API Route的请求中似乎有不同的字符

ajax node.js axios next.js

6
推荐指数
0
解决办法
1638
查看次数

如何在 NextJS SSR 中存储和获取 access_token

我将 NextJS 与服务器端渲染结合使用

我使用带有 access_token (JWT) 的身份验证服务

我无法将 access_token 存储在中,localStorage因为它在中不可用getServerSideProps

所以我将 access_token 放入httpOnly cookie服务器上可用。

我在服务器上有一些请求,在客户端上有一些请求,所以我需要通过两种方式获取access_token,在服务器上req.headers.cookie和在客户端上document.cookie

我想编写 axios 拦截器以将 access_token 添加到每个请求中。

这适用于客户端,但我能为服务器端做什么?

import axios from 'axios';

const _axios = axios.create();
axiosInstance.interceptors.request.use(function (config) {
  let token;

  // check if it's on the client-side
  if(typeof document !== 'undefined')
     token = getToken(document.cookie);

  // how to check for server-side and how to get cookie ?

  return {
    ...config,
      headers: {
      'Authorization': `Bearer ${token}`
    }
  };
}, function …
Run Code Online (Sandbox Code Playgroud)

node.js jwt reactjs axios next.js

5
推荐指数
1
解决办法
3286
查看次数

标签 统计

axios ×2

next.js ×2

node.js ×2

ajax ×1

jwt ×1

reactjs ×1