小编Iva*_*van的帖子

在 Express 中访问文件上传 formData

如何访问 API 中的文件?

我阅读了其他解决方案,它们都需要 npm 包来解决这个问题。我想明白为什么我不能做到香草。另外,答案很旧,建议使用 body-parser,它现在与 Express 捆绑在一起。

我希望解决方案是普通 JS,以便更好地理解该过程。

客户

async function uploadFile(file) {
    let formData = new FormData();
    formData.append("file", file);

    let res = await fetchPostFile("/api/files", formData);
}
Run Code Online (Sandbox Code Playgroud)

拿来

export async function fetchPostFile(url, formData) {
    try {
        let result = await (
            await fetch(url, {
                method: "POST",
                withCredentials: true,
                credentials: "include",
                headers: {
                    Authorization: localStorage.getItem("token"),
                    Accept: "application/json",
                    "Content-type": "multipart/form-data",
                },
                body: formData,
            })
        ).json();

        return result;
    } catch (err) {
        return err;
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序编程接口

router.post("/api/files", async function …
Run Code Online (Sandbox Code Playgroud)

upload fetch node.js express

8
推荐指数
2
解决办法
1万
查看次数

Slim 3 Framework - 我应该为我的API使用路由组吗?

我应该使用这种结构......

require 'vendor/autoload.php';
$app = new \Slim\App;

$app->get('/books', 'getBooks');
$app->get('/books/{id}', 'getBook');

$app->run();

function getBooks() {
    // Return list of books
}

function getBook($id) {
    // Return a single book
}
Run Code Online (Sandbox Code Playgroud)

或者这个"路线组"一个?

require 'vendor/autoload.php';
$app = new \Slim\App;

$app->group('/books', function () use ($app) {
    $app->get('', function ($req, $res) {
        // Return list of books
    });

    $app->get('/{id:\d+}', function ($req, $res, $args) {
        // Return a single book
    });
});

$app->run();
Run Code Online (Sandbox Code Playgroud)

有什么更好的方法?前者似乎更清洁.我比较新,所以我不知道利弊.

php api rest slim

6
推荐指数
1
解决办法
5096
查看次数

How to focus next input on pressing enter, in functional components? (TAB behavior)

I want to implement the TAB behavior, but with pressing ENTER.

Here is my attempt to solve it, but it doesn't work due to not using Refs.

My idea is to state in each input, which element should be focused next, and the Enter keyup event handler setting that value as the new focused field.

I've seen examples using useHook but I can't figure how to use it, without spamming a ton of useState's for each input.

Here …

javascript reactjs

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

nginx 显示 IP 地址而不是域名

我有一条 godaddy A 记录指向我的 Digital Ocean IP 地址。

这是 nginx 配置。

server {
    listen 80 default_server;
    server_name domain.com www.domain.com;
    location / {
       proxy_pass 'http://127.0.0.1:3004';
    }
}
Run Code Online (Sandbox Code Playgroud)

当我输入时,domain.com它会转到服务器,但地址栏显示 IP 地址。

怎么才能显示域名呢?

dns nginx

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

Svelte (rollup) - 错误:意外的令牌(注意你需要@rollup/plugin-json 来导入 JSON 文件)

我没有做任何事情来触发这个错误。该应用程序前一秒运行良好,下一秒就不行了。

为什么会这样?这不是因为缺少@rollup/plugin-json插件,因为它以前没有它就可以工作。

错误

https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
path (imported by  path?commonjs-external)
http (imported by  http?commonjs-external)
net (imported by  net?commonjs-external)
url (imported by  url?commonjs-external)
[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
node_modules/mime-db/db.json (2:40)
1: {
2:   "application/1d-interleaved-parityfec": {
                                           ^
3:     "source": "iana"
4:   },
Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
    at error (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:5265:30)
    at Module.error (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:9835:16)
    at tryParse (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:9716:23)
    at Module.setSource (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:10142:19)
    at ModuleLoader.addModuleSource (/mnt/c/ivan/dev/lab/atlas-biotek/node_modules/rollup/dist/shared/rollup.js:18312:20)
Run Code Online (Sandbox Code Playgroud)

添加插件

npm i …
Run Code Online (Sandbox Code Playgroud)

rollup svelte

5
推荐指数
2
解决办法
2397
查看次数

如何发出 Google Translate API V3 简单的 HTTP POST 请求?

我知道文档是存在的……这真是该死的神秘和复杂,典型的过度设计。它必须更简单。

我不想使用第三方库...我想要一个漂亮的普通 js 获取。

我正在尝试以下操作nodejs...

let url = `https://translation.googleapis.com/v3/projects/PROJECT_ID:translateText?key=API_KEY`;

let response = await fetch(url, {
    method: "POST",
    withCredentials: true,
    credentials: "include",
    headers: {
        Authorization: "bearer",         
        "Content-Type": "application/json",
    },
    body: {
        sourceLanguageCode: "en",
        targetLanguageCode: "ru",
        contents: ["Dr. Watson, come here!"],
        mimeType: "text/plain",
    },
});

let result = await response.json();

console.log(result);
Run Code Online (Sandbox Code Playgroud)

并收到此错误:

{ error:
   { code: 401,
     message:
      'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.', …
Run Code Online (Sandbox Code Playgroud)

javascript http google-api node.js

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

现场和档案中的服务员没有开火

昨天它还有效,现在它停止了,没有对代码进行任何更改。到底是怎么回事?

客户

async function uploadFile(file) {
    let formData = new FormData();

    formData.append("recordUid", recordUid);
    formData.append("fieldUid", fieldUid);
    formData.append("file", file);

    await fetchPostFormData("/api/files", formData);
}

async function fetchPostFormData(url, formData) {);
    try {
        let result = await (
            await fetch(url, {
                method: "POST",
                withCredentials: true,
                credentials: "include",
                headers: {
                    Authorization: localStorage.getItem("token"),
                },
                body: formData,
            })
        ).json();

        return result;
    } catch (err) {
        return err;
    }
}
Run Code Online (Sandbox Code Playgroud)

服务器

router.post("/api/files", async (req, res, next) => {
    try {
        console.log("starting upload..."); // <------------------- THIS ONE IS LOGGED

        let …
Run Code Online (Sandbox Code Playgroud)

file-upload node.js express busboy

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

通过 Node Express 将对象作为字符串而不是 JSON 发送

好的,我希望响应是一个纯字符串,而不是 JSON。

前任。这个对象

let obj = {
  foo: 'bar',
  baz: 1
}
Run Code Online (Sandbox Code Playgroud)

应该返回为

"{foo: 'bar', baz: 1}"
Run Code Online (Sandbox Code Playgroud)

代替

{"foo": "bar", "baz": 1}
Run Code Online (Sandbox Code Playgroud)

为什么?我需要使用字符串作为快速图表中的链接

"{foo: 'bar', baz: 1}"
Run Code Online (Sandbox Code Playgroud)

JSON 中的双引号破坏了图像链接。

或者,也许建议一个更好的方法。

html javascript json object node.js

4
推荐指数
1
解决办法
286
查看次数

React Components - 创建它们的正确方法是什么?

我正在学习React,我遇到了两种创建组件的方法.一个是Facebook,另一个是AirBnB.我也在我一直在看的教程中看到过它们.

这可能是一个愚蠢的问题,但哪一个更好?

Facebook的:

var React = require("react");

var Component = React.createClass({
    render: function(){
        return (
            <div>{this.props.item}</div>
        );
    }
});

module.exports = Component;
Run Code Online (Sandbox Code Playgroud)

制作的Airbnb:

import React from "react";

export default class Component extends React.Component {
    render() {
        return (
            <div>{this.props.item}</div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

免责声明:我可能在代码中有错误,所以请原谅我,只关注风格.

javascript frontend components jsx reactjs

3
推荐指数
1
解决办法
1193
查看次数

SQL注入生成的查询有多安全?

我正在尝试创建一个可以使用多个单词的搜索栏,但我担心SQL注入.

我使用节点快递故宫MSSQL包.

这是获取条件的代码,生成SQL并运行它:

router
.get('/search/:criteria', function (req, res) {
    var criteria = req.params.criteria;
    var words = criteria.split(" ");

    var x = ""
    words.map(word => x += `name like '%${word}%' and `);
    x = x.substring(0, x.length - 5); // Remove trailing 'and'

    var query = `SELECT * FROM table WHERE ${x}`

    new sql.ConnectionPool(db).connect().then(pool => {
        return pool.request().query(query)
    }).then(result => {

    })
});
Run Code Online (Sandbox Code Playgroud)

搜索something to search将导致此查询:

SELECT * FROM table 
WHERE 
    name like '%something%'
    and name …
Run Code Online (Sandbox Code Playgroud)

sql sql-server sql-injection node.js express

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

是的,自定义错误消息不在 ValidationError 对象中

ValidationError对象不具有自定义错误消息。

let data = {
    foo: "aaa"
}

let schema = 
    yup.object().shape({
        foo: yup.number().integer('Custom "must be a number" error message!')
    });

try {

    let validated = await schema.validate(data, { abortEarly: false })

} catch (err) {
    console.log(err.errors[0]) // foo must be a `number` type, but the final value was: `NaN`
    console.log(err.inner[0].message) // foo must be a `number` type, but the final value was: `NaN`
}
Run Code Online (Sandbox Code Playgroud)

我应该Custom "must be a number" error message!err.inner[0].message.

这是代码和框。 …

javascript validation yup

0
推荐指数
1
解决办法
6408
查看次数

SSH pm2:找不到命令

当我从本地计算机运行此命令时...

ssh user@123.456.789.255 "pm2 reload all"
Run Code Online (Sandbox Code Playgroud)

我收到这个错误...

pm2: command not found
Run Code Online (Sandbox Code Playgroud)

在远程计算机中运行命令工作正常,所以这不是路径问题?

ssh pm2

0
推荐指数
1
解决办法
560
查看次数