如何访问 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) 我应该使用这种结构......
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)
有什么更好的方法?前者似乎更清洁.我比较新,所以我不知道利弊.
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.
我有一条 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 地址。
怎么才能显示域名呢?
我没有做任何事情来触发这个错误。该应用程序前一秒运行良好,下一秒就不行了。
为什么会这样?这不是因为缺少@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) 我知道文档是存在的……这真是该死的神秘和复杂,典型的过度设计。它必须更简单。
我不想使用第三方库...我想要一个漂亮的普通 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) 昨天它还有效,现在它停止了,没有对代码进行任何更改。到底是怎么回事?
客户
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) 好的,我希望响应是一个纯字符串,而不是 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 中的双引号破坏了图像链接。
或者,也许建议一个更好的方法。
我正在学习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)
免责声明:我可能在代码中有错误,所以请原谅我,只关注风格.
我正在尝试创建一个可以使用多个单词的搜索栏,但我担心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) 该烨 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
.
当我从本地计算机运行此命令时...
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)
在远程计算机中运行命令工作正常,所以这不是路径问题?
javascript ×5
node.js ×5
express ×3
reactjs ×2
api ×1
busboy ×1
components ×1
dns ×1
fetch ×1
file-upload ×1
frontend ×1
google-api ×1
html ×1
http ×1
json ×1
jsx ×1
nginx ×1
object ×1
php ×1
pm2 ×1
rest ×1
rollup ×1
slim ×1
sql ×1
sql-server ×1
ssh ×1
svelte ×1
upload ×1
validation ×1
yup ×1